Part Number Hot Search : 
PIP250M 3DD10 DELAY 74HC14B SL887 SL887 BAS70W X9315Z
Product Description
Full Text Search
 

To Download ST9 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  january 2004 1/146 rev. 1.5 ST9 user guide 1 about this guide welcome to the ST9 user guide. the aim of this book is to help you to get a working knowl- edge of the ST9 microcontroller family. using this foundation, you will be in a good position to understand and implement any of the ST9 microcontrollers. to make it easier, we have se- lected the major technical concepts of the ST9 family and will introduce them gradually over several chapters, always supporting theory with practical examples. 1.1 prerequisites this book addresses application developers. to fully benefit from the book content, you should be familiar with microcontrollers and their associated development tools. for basic information on microcontrollers and development tools, you should refer to one of the many introductory books available on the subject. 1.2 results the book will provide you with:  a basic understanding of the ST9 microcontroller family  knowledge and ready-to-use examples on using ST9 peripherals  useful tips and warnings 1
2/146 table of contents 146 1 1 about this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.3 how to use this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 companion software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.5 about the authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.6 related documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2 introducing the ST9 basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.1 processor core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.2 peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.2.1 ST92f124 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2.2 ST92f150 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2.3 ST92f250 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3 processor core: main concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.1 address spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.1.1 register-oriented programming model . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.1.2 register file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.1.3 direct access to the register file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.1.4 working registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.1.5 peripheral register pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.1.6 working registers and register pointers . . . . . . . . . . . . . . . . . . . . . . . . 16 3.1.7 memory management unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 3.2 stack modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.3 instruction set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.3.1 overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.3.2 advantages when using c language . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.4 interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.4.1 interrupt vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 3.4.2 interrupt priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 3.4.3 external interrupt unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 3.5 dma controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 3.5.1 overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 3.5.2 how the dma works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 3.6 reset and clock control unit (rccu) . . . . . . . . . . . . . . . . . . . . . . . 60 3.6.1 clock control unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 3.6.2 reset and stop manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 4 using the on-chip peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.1 programming the core and peripherals . . . . . . . . . . . . . . . . . . . . 65 4.2 parallel i/o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3/146 table of contents 1 4.3 standard and watchdog timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.3.1 description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 4.3.2 timer application for periodic interrupts . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.3.3 watchdog application 1: generating a pwm . . . . . . . . . . . . . . . . . . . . . 73 4.3.4 watchdog application 2: using the watchdog . . . . . . . . . . . . . . . . . . . . 74 4.4 multifunction timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 4.4.1 generating two pulse width modulated waves with one mft . . . . . . . 79 4.4.2 generating a pulse width modulated wave with a cleaner spectrum . . 82 4.4.3 incremental encoder counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 4.4.4 mft application 1: generating 2 pwms using interrupts . . . . . . . . . . . . 86 4.4.5 mft application 2: generating a pwm using dma . . . . . . . . . . . . . . . . 86 4.4.6 mft application 3: generating a pwm using the dma swap mode . . . 87 4.5 serial peripheral interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.5.1 description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.5.2 static liquid-crystal display interface example . . . . . . . . . . . . . . . . . . . 88 4.5.3 eeprom serial interface example using i2c . . . . . . . . . . . . . . . . . . . . . 91 4.6 serial communications interface . . . . . . . . . . . . . . . . . . . . . . . . . . 92 4.6.1 description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 4.6.2 sci application 1: sending bytes using interrupts . . . . . . . . . . . . . . . . . 97 4.6.3 sci application 2: sending bytes using dma . . . . . . . . . . . . . . . . . . . . . 97 4.6.4 sci application 3: sending and receiving bytes using dma . . . . . . . . . 97 4.6.5 sci application 4: matching input bytes . . . . . . . . . . . . . . . . . . . . . . . . . 97 4.7 analog to digital converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 4.7.1 description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 4.7.2 analog watchdog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 4.7.3 interrupt vectoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 4.7.4 adc application: a/d conversions and analog watchdog using interrupts 101 4.8 peripheral initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 4.8.1 initialization header file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 4.8.2 peripheral function file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 5 using the development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.1 developing in c language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.2 available tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.3 introducing the development tools . . . . . . . . . . . . . . . . . . . . . . 113 5.4 program configuration and initialisation . . . . . . . . . . . . . . . . . 113 5.4.1 writing the makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 5.4.2 writing the linker command file using a script file . . . . . . . . . . . . . . . 119 5.4.3 writing the start-up file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 5.5 global initialisation: core and peripherals . . . . . . . . . . . . . . . 129 5.5.1 core initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 5.5.2 peripheral initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4/146 table of contents 146 1 5.5.3 port initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 5.5.4 final initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 5.6 interrupt considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 6 detailed block diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 6.7 external interrupt controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 6.8 top-level interrupt input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 6.9 watchdog timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 6.10 multifunction timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 6.11 adc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 7 glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
5/146 ST9 user guide 1.3 how to use this guide as a first approach, we recommend that you study each chapter in sequence and carry out the exercises at each step. 1.4 companion software a downloadable file entitled ST9 user guide companion software is available. this file pro- vides all the source text files, listings, object files and any other files mentioned in the docu- ment. you can download the ST9 user guide companion software from the http://www.stmcu.com website product support page. unless otherwise specified, all the examples can be compiled for ST92f124/ST92f150/ST92f250 by modifying the makefile and the ? device.h ? file, if in- cluded in the application directory. 1.5 about the authors this user guide has been initially written by jean-luc gr goriad s and jean-marc delaplace and revised for the ST9 by jean-luc cr bouw. jean-luc cr bouw a signal processing engineer, he has developed a voice synthesizer with an ST9 and con- ducts ST9 training programs. he acts as a field application engineer consultant for all stmi- croelectronics microcontrollers. jean-marc delaplace a former electronics design engineer, he has worked throughout his career for various u.s. companies involved in lab automation equipment. he has used microprocessors since they first appeared on the market and programmed microcontrollers of various brands in industrial applications using both assembler and high-level languages. jean-luc gr goriad s teaches automated systems and industrial computer science at the electrical engineering de- partment of the university of cergy-pontoise. he introduced the stmicroelectronics st6 as a teaching base for his microcontroller course. on this occasion, he wrote with his friend j.m delaplace, the book ? le st6: etude progressive d'un microcontr ? leur ? published at ? editions dunod ? . 1
6/146 ST9 user guide 1.6 related documents the following reference documents should be available for additional information: ? ST9 datasheet ? ST9 programming manual ? ST9 family gnu software tools ? ST9 gnu c toolchain release note ? ST9 family gnu c compiler ? gnu make utility you can get a current list of documentation at http://www.stmcu.com.
7/146 ST9 user guide 2 introducing the ST9 basics the ST9 microcontroller family has a common processor core surrounded by a range of pow- erful peripherals for interfacing with many different devices. the peripherals have sufficient built-in intelligence to be able to perform even complex jobs on their own, freeing the core al- most entirely from i/o handling. the core can thus be fully utilized for classical micropro- cessing tasks. the ST9 architecture is an original stmicroelectronics design, with the objective of providing an innovative and efficient microcontroller architecture dedicated to real-time control. 2.1 processor core when you compare different microcontrollers, you can estimate the relative computing power of the core, and also of the peripherals (if they include some intelligence). in some architec- tures, the peripherals make heavy use of the core and thus take up a part of its computing power. many microcontrollers available on the market have a relatively powerful core, sur- rounded by very simple peripherals. this approach has the advantage of making the periph- erals easy to use and configure, but at the expense of the overall computing power. the ST9 is an example of a radically different compromise. its core is among the best 8-bit mi- croprocessors on the market in terms of computing performance and system management ca- pabilities. it is assisted (rather than just surrounded) by peripheral blocks of which most can perform complex tasks without the intervention of the core. the net result is a powerful ma- chine that can even perform impressive tasks just using its peripherals. the three applications described in this book give meaningful examples of processes handled solely by the periph- erals. the ST92f150 is the latest generation of the powerful ST9 microprocessor family. the new ST9 core executes software more than three times faster than the previous ST9 core using optimized instructions and up to double the cpu frequency. the core as well as many periph- erals have been enhanced, like for example, the memory management unit (mmu), which is now more flexible, with a single 4-mbyte memory space that is directly accessible without using bank switching. another example is the reset and clock control unit (rrcu) which has added features for reducing power-consumption. the ST9 is a register-oriented machine. this means that a large number of registers is avail- able in the core; but above all, this implies that the instruction set is tailored to make efficient use of its registers through optimized addressing modes. it is also well suited to the use of c language.
8/146 ST9 user guide 2.2 peripherals the ST9 family includes a large number of peripherals. the main ones are: these peripherals are available with the standard variants. more peripherals are available on custom devices on request, e.g. a videotext decoding logic. the ST9 family includes so many variants it would go beyond the scope of this book to de- scribe them all. they are all made up of the same ST9 core surrounded by a set of peripherals, rom and/or ram and/or eeprom and/or flash being optional. this book has chosen to show the three most generic variants and provide a basis for understanding all the others. acronym name function mft multi-function timer all counting and timing functions. includes auto-reload on con- dition, interrupt generation, dma transfer, two inputs for fre- quency measurement or pulse counting, two outputs that can change on condition, pwm signal generation. conditions include: overflow/underflow, comparison with one or two compare registers. capture registers used to record transitions on inputs with their time of occurrence. sci-m serial communication in- terface asynchronous transfer with either internal bit-rate generation or an external clock. parity generation/detection. address recog- nition feature that can request an interrupt on match of an input character. dma transfer. wdt watchdog timer can be used either as a watchdog or as a timer with input and output capable of pulse counting or waveform generation. i/o port parallel input/output port parallel input/output ports. each bit individually configurable as input, output, bi-directional, or alternate function. inputs can be high impedance or with pull-up, cmos or ttl-level. outputs can have open drain or push-pull configuration. adc analog to digital converter. 10-bit analog to digital converter. one to sixteen channels can be converted in series. on each of two of the sixteen channels, an analog watchdog function is used to define two thresholds. when exceeded, an interrupt is generated.
9/146 ST9 user guide 2.2.1 ST92f124 figure 1 .ST92f124r9 block diagram 256 bytes register file ram 2 kbytes ST9 core 8/16 bits cpu interrupt management memory bus rccu register bus watchdog nmi miso mosi sck ss st. timer spi sda scl i 2 c bus sci m flash 64 kbytes txclk rxclk sin dcd sout clkout rts wdout hw0sw1 stout fully prog. i/os p0[7:0] p1[2:0] p2[7:0] p3[7:4] p4[7:4] p5[7:0] p6[5:2,0] p7[7:0] mf timer 0 tinpa0 touta0 tinpb0 toutb0 tinpa1 touta1 tinpb1 toutb1 int[5:0] wkup[13:0] mf timer 1 e 3 tm 1 kbyte oscin oscout reset clock2/8 intclk ck_af adc av dd av ss ain[15:8] extrg v reg voltage regulator the alternate functions ( italic characters ) are mapped on port 0, port 1, port2, port3, port4, port5, port6 and port7.
10/146 ST9 user guide figure 2 . ST92f124v1 block diagram 256 bytes register file ram 4 kbytes ST9 core 8/16 bits cpu interrupt management memory bus rccu ext. mem. address data port0 ext. mem. address ports 1,9 register bus watchdog as ds r w wait nmi ds2 rw miso mosi sck ss a[10:8] a[21:11] a[7:0] d[7:0] st. timer spi sda scl i 2 c bus flash 128 kbytes wdout hw0sw1 stout fully prog. i/os p0[7:0] p1[7:3] p1[2:0] p2[7:0] p3[7:4] p3[3:1] p4[7:4] p4[3:0] p5[7:0] p6[5:2,0] p6.1 p7[7:0] p8[7:0] p9[7:0] mf timer 0 tinpa0 touta0 tinpb0 toutb0 tinpa1 touta1 tinpb1 toutb1 int[6:0] wkup[15:0] mf timer 1 e 3 tm 1 kbyte oscin oscout reset clock2/8 intclk ck_af adc av dd av ss ain[15:8] ain[7:0] extrg v reg voltage regulator the alternate functions ( italic characters ) are mapped on port 0, port 1, port2, port3, port4, port5, port6, port7, port8 and port9. icapa0 ocmpa0 icapb0 ocmpb0 extclk0 icapa1 ocmpa1 icapb1 ocmpb1 extclk1 ef timer 0 ef timer 1 sci m txclk rxclk sin dcd sout clkout rts sci a rdi tdo
11/146 ST9 user guide 2.2.2 ST92f150 figure 3 .ST92f150c(r/v)1/9 block diagram 256 bytes register file ram 2/4 kbytes ST9 core 8/16 bits cpu interrupt management memory bus rccu ext. mem. address data port0 ext. mem. address ports 1,9* register bus watchdog as ds r w wait nmi ds2 rw* miso mosi sck ss a[10:8] a[21:11]* a[7:0] d[7:0] st. timer spi sda scl i 2 c bus flash 128/64 kbytes wdout hw0sw1 stout * not available on 64-pin version. fully prog. i/os p0[7:0] p1[7:3]* p1[2:0] p2[7:0] p3[7:4] p3[3:1]* p4[7:4] p4[3:0]* p5[7:0] p6[5:2,0] p6.1* p7[7:0] p8[7:0]* p9[7:0]* mf timer 0 tinpa0 touta0 tinpb0 toutb0 tinpa1 touta1 tinpb1 toutb1 int[5:0] int6 * wkup[13:0] wkup[15:14]* mf timer 1 e 3 tm 1 kbyte oscin oscout reset clock2/8 intclk ck_af adc av dd av ss ain[15:8] ain[7:0]* extrg rx0 tx0 can_0 v reg voltage regulator the alternate functions ( italic characters ) are mapped on port 0, port 1, port2, port3, port4, port5, port6, port7, port8* and port9*. icapa0 ocmpa0 icapb0 ocmpb0 extclk0 icapa1 ocmpa1 icapb1 ocmpb1 extclk1 ef timer 0 * ef timer 1 * sci m txclk rxclk sin dcd sout clkout rts sci a* rdi tdo
12/146 ST9 user guide figure 4 . ST92f150jdv1 block diagram 256 bytes register file ST9 core 8/16 bit cpu interrupt management memory bus rccu register bus watchdog as ds r w wait nmi ds2 rw miso mosi sck ss ef timer 0 st. timer spi sci m txclk rxclk sin dcd sout clkout rts wdout hw0sw1 stout icapa0 ocmpa0 icapb0 ocmpb0 extclk0 fully prog. i/os p0[7:0] p1[7:0] p2[7:0] p3[7:1] p4[7:0] p5[7:0] p6[5:0] p7[7:0] p8[7:0] p9[7:0] rdi tdo mf timer 0 tinpa0 touta0 tinpb0 toutb0 icapa1 ocmpa1 icapb1 ocmpb1 extclk1 tinpa1 touta1 tinpb1 toutb1 int[6:0] wkup[15:0] ef timer 1 mf timer 1 sci a oscin oscout reset clock2/8 clock2 intclk ck_af adc av dd av ss ain[15:0] extrg sda scl i 2 c bus vpwi vpwo j1850 jblpd a[7:0] d[7:0] a[21:8] ext. mem. address data port0 ext. mem. address ports 1,9 ram 6 kbytes flash 128 kbytes e 3 tm 1k byte the alternate functions ( italic characters ) are mapped on port0, port1, port2, port3, port4, port5, port6, port7, rx0 tx0 can_0 rx1 tx1 can_1 v reg voltage regulator port8 and port9. rdi tdo flash 128 kbytes
13/146 ST9 user guide 2.2.3 ST92f250 figure 5 . ST92f250cv2 block diagram 256 bytes register file ST9 core 8/16 bit cpu interrupt management memory bus rccu register bus watchdog as ds r w wait nmi ds2 rw miso mosi sck ss ef timer 0 st. timer spi sci m txclk rxclk sin dcd sout clkout wdout hw0sw1 stout icapa0 ocmpa0 icapb0 ocmpb0 fully prog. i/os p0[7:0] p1[7:0] p2[7:0] p3[7:0] p4[7:0] p5[7:0] p6[7:0] p7[7:0] p8[7:0] p9[7:0] rdi tdo mf timer 0 tinpa0 touta0 tinpb0 toutb0 icapa1 ocmpa1 icapb1 ocmpb1 tinpa1 touta1 tinpb1 toutb1 int[6:0] wkup[15:0] ef timer 1 mf timer 1 sci a oscin oscout reset clock2/8 clock2 intclk adc av dd av ss ain[15:0] extrg sda1 scl1 i 2 c bus _1 a[7:0] d[7:0] a[21:8] ext. mem. address data port0 ext. mem. address ports 1,9 ram 8 kbytes flash 256 kbytes e 3 tm 1k byte the alternate functions ( italic characters ) are mapped on port0, port1, port2, port3, port4, port5, port6, port7, rx0 tx0 can_0 v reg voltage regulator port8 and port9. sda0 scl0 i 2 c bus _0
14/146 ST9 user guide 3 processor core: main concepts the term ST9 designates a family of components. each component shares the same core, surrounded by a particular configuration of memory and peripherals that make up the specific variant. the ST9 core has a unique and powerful structure. this chapter explains the main building blocks that you need to get familiar with to be able to make full use of its capabilities. the main features of the core architecture are: ? register-oriented programming model ? single-space memory addressing ? system and user stacks ? interrupt system with fully integrated controller ? built-in dma mechanism ? reset and clock control unit (rccu) with pll 3.1 address spaces the ST9 provides two different address spaces: register space and memory space. the register space draws its power from its size: 256 registers of which 224 are uncommitted, and from the fact that it can hold data or pointers to data that reside in any of the two spaces. the memory spaces can address up to 4 mbytes. this address space is arranged as 64 seg- ments of 64 kbytes to address programs and as 256 segments of 16 kbytes to address data when the dma is not used. 3.1.1 register-oriented programming model the usual microprocessor core structure is based on an accumulator. the accumulator is the one register that holds the data to work on and the results of the arithmetic or logical opera- tions applied to it. this structure has become a classic - for its simplicity - the internal data paths of the microprocessor all converge to the accumulator. the instruction set is simple, since you need to specify only one memory address in a data move instruction, the other being implicit: the accumulator itself. this simplicity has its own drawbacks: the accumulator is the computation bottleneck, since to move data from one place in memory to another place, you have to do it through the accumu- lator. the simplest transfer involves at least two instructions: one to get the data, the other one to store it. register-oriented models, in contrast, allow you to move data directly from one place to an- other in a single instruction. data can come from a register or from a memory address and can go to either to a register or a memory address. you can code the addresses in the instruction, or store them in registers referenced by the instruction. this allows you to optimize your code
15/146 ST9 user guide by choosing to store frequently used data in registers, leaving less frequently used data in memory. 3.1.2 register file the ST9 has a special addressing space for registers, providing 256 different register ad- dresses. this large amount of registers gives you considerable flexibility in allocating vari- ables. register addresses are coded using one byte. you can use any of these registers to hold data or as a pointer either to other registers or to bytes in memory (1) . contrast this with processors that feature a certain number of registers, but in which some of these registers are meant to be only pointers or indexes, and some others not. these processors only allow trans- fers between memory and registers. the register organization of the ST9 gives you a real ad- vantage you can make use of. 3.1.3 direct access to the register file the entire register file can be accessed directly by its address prefixed by an ? r ? except for register group d (13) that can only be addressed through the working register mechanism. for example to address the register at the address 73, address it as r73, r49h or r1001001b in decimal, hexadecimal or binary. for a double register (16 bits) you can use the ? rr ? prefix to address any data with an even address. any register can be given a user-defined name. in c language: #pragma register_file data1 char data1; #pragma register_file data2 60 int data2; and accessed with: data1=13; data2=0x1234; data1 is automatically allocated in the register file by the linker as no register number is pro- vided. data2 is manually allocated in register rr60. this pragma should be repeated in each file where the variable is made visible through an external declaration. however using these registers needs an additional byte with the instruction mnemonic. using working registers is more efficient, because it avoids using this address byte. (1) except for group e (14) reserved for the system registers and group f (15) reserved for the peripherals.
16/146 ST9 user guide 3.1.4 working registers to further improve coding efficiency, a special mechanism has been created: the concept of working registers. this reduces to just 16 bytes the register space accessible by the instruc- tions in the so-called working register addressing mode. only four bits are required to address this space, allowing both the source and the destination of a data move to be coded in a single byte, thus saving both code size and execution time. 256 registers, when split into groups of 16, give 16 groups. the group used is indicated in a special register, called the working register pointer . the register address is made up of the group number and the register address within the group, as follows: figure 6 . register group addressing scheme 3.1.5 peripheral register pages all internal peripherals are mapped into the register space. most of them have a multitude of features and can be configured in different ways. this implies that they have a large number of registers. since only the last group of 16 registers is allocated for peripherals, a special scheme must be used to overcome this problem. it is called paging. the last group of registers actually addresses one pack of sixteen registers that belongs to the peripheral itself. which pack of which peripheral depends on the value of a register called the page pointer register . there can be as many as 64 different pages, providing plenty of space for accessing periph- erals. here are more details on these two mechanisms. 3.1.6 working registers and register pointers the working registers offer a workspace of 16 bytes. this is sufficient for most applications, and much more convenient than a single accumulator. however, in some applications, this is still not enough. in this case you can easily allocate more than one register group to a partic- ular program module. since any register can be accessed directly, it is up to you to decide whether you want to switch working register groups or not to access the other groups of reg- isters. since changing the current group involves only one instruction, the concept of working regis- ters can greatly reduce context switching time, for example in the case of an interrupt service 7 6 5 4 3 2 1 0 register address group number (16 register groups) register number within group number
17/146 ST9 user guide routine. doing this preserves the contents of the whole group, and the reverse operation re- stores them, as in the example: ; the main program uses the working register group 0 interruptroutine: pushw rpp ; keep track of current group srp #2 ; switch to group 1 (see text below for details) ... ... ; body of the interrupt service routine ... popw rpp ; restore whatever group was active iret ; return from interrupt supposing we could not switch working registers, we would have to push 16 bytes to the stack to ensure that the contents of the working area have been preserved, and pop them back be- fore returning. obviously the example above is more efficient, both in code and data memory size, and also in execution time. you use register pointers to allocate the working registers in a particular group. when writing in c or assembly language, you must position the working registers before you use them (2) . switching groups involves the rpp register pair, made of the two registers rp0 and rp1. these registers are directly accessible, but since their bits are laid out in a non-trivial manner, it is recommended that you set them using only one of the srp , srp0 or srp1 instructions. the registers are considered as sixteen groups of sixteen registers each. this is the way they are represented in the register number summary table (see table 1. ). use the numbers in this table to refer to a register directly, e.g. when writing r35, this designates the fourth register of group 2. 3.1.6.1 switching the 16 groups of working registers this is done using the srp instruction. in spite of what we have explained up until now, and how it is usually represented, the core does not actually divide the registers in 16 groups of 16 registers, but 32 blocks of 8 registers. this is why the srp instructions require arguments ranging from 0 to 31 instead of 0 to 15. here is how the register pointers select the desired register group among 16 such groups. (2) device datasheet; address spaces of the register file 2.2.1 and following, system regis- ters 2.3.
18/146 ST9 user guide figure 7. selecting a 16-register working group using srp defines one group of sixteen working registers named r0 to r15, and occupying 16 contiguous registers in the register file. the lower case r for the register number indicates that it is a working register number, in contrast to upper case r registers that indicate an absolute register number. for example, accessing r3 is the same as accessing r19 if the current group is group 1: srp #2 ; switch to group 1 inc r3 ; increment 4th register of the group group f paged registers group e system registers r255 r240 r239 r224 r223 r00 r15 r16 r31 r32 group 0 groups 2 to d register pointer 0 (rp0r) r232 r15 r0 group 1 as working register group rp0r loaded using instruction code srp #2 general purpose registers
19/146 ST9 user guide inc r19 ; increment the same register again the following table summarizes the use of the srp instruction and its effect in terms of group selection. table 1. register page number summary notes : though it is possible, it normally makes no sense to set the working register group either to group e (14) or f (15), since the registers in these groups have pre-defined meanings. you can- not use them to store intermediate values of calculations without greatly affecting the behavior of the microcontroller in an unpredictable way. however, bit-level instructions are only available using working register addressing, so when you need to do bit manipulations in these groups, setting the register pointer to either 28 or 30 is an efficient way of programming when accessing these two groups. the srp instruction is the only one you have to use to switch register groups, and is the way working registers are used in most programs. however, the working register scheme includes a subtlety that is seldom used, but that could give you even more flexibility in some cases. this is what is described in the next paragraph. the same register group number can be selected by an odd or even number. in fact, the for- mula is: srp 2*n+1 ; for group n or srp 2*n ; for group n hexadecimal register number decimal register number function register group decimal (hexadecimal) srp #n instruction to select a group to provide r0-r15 f0-ff 240-255 paged registers 15 (f) srp #30 e0-ef 224-239 system registers 14 (e) srp #28 d0-df 208-223 general purpose registers 13 (d) srp #26 c0-cf 192-207 12 (c) srp #24 b0-bf 176-191 11 (b) srp #22 a0-af 160-175 10 (a) srp #20 90-9f 144-159 9 srp #18 80-8f 128-143 8 srp #16 70-7f 112-127 7 srp #14 60-6f 96-111 6 srp #12 50-5f 80-95 5 srp #10 40-4f 64-79 4 srp #8 30-3f 48-63 3 srp #6 20-2f 32-47 2 srp #4 10-1f 16-31 1 srp #2 00-0f 00-15 0 srp #0
20/146 ST9 user guide 3.1.6.2 defining two separate groups of eight working registers in this mode, the srp instruction is not used. instead, we use the pair of instructions srp0 and srp1 . when using a working register, r0 to r7 address the first to the eighth register of the whole group selected by half the value in rp0 i.e. all the registers of the half group selected by rp0. registers r8 to r15 relate to the first to the eighth register of the group pointed to by rp1. here is how the two blocks are selected: figure 8 . register numbers group f paged registers group e system registers r255 r240 r239 r224 r223 r00 r15 r16 r31 r32 groups 2 to c register pointer 0 (rp0r) r232 r7 r0 lower part of group 1 as working register group rp0r loaded using the instruction code srp0 #2 general purpose registers register pointer 1 (rp1r) r233 r23 r24 rp1r loaded using the instruction code srp1 #27 upper part of group d as working register group group 0 r216 r8 r15 upper part of group 1 lower part of group d r208 r215 r207
21/146 ST9 user guide as an example, if rp0 is set to half group 2 (lower part of whole group 1) and rp1 to half group 27 (upper part of whole group 13), r0 will designate r16 (2 x 8 + 0) while r15 designates r223 (27 x 8 + 7). using either method depends on the organization of the data in the register file. you may find it convenient to use two 8-register blocks if you need to make quick calculations on pairs of data that are far apart in the register file. the page numbering and switching instructions are summarized below: table 2. register page number summary when you use an 8- or 16-register group, you may very likely have a subroutine or an interrupt routine that uses a different set of working registers. you must save (push) the pair of register pointers rpp that include rp0 and rp1 at the beginning of the routine and restore them on exit. 3.1.6.3 peripheral register paging group f of the 16-register groups is paged so that as many as 64 different groups can be mapped to this address range. this large space is used to accommodate the registers related to the peripherals. the paging technique allows you to add any number of peripherals and still be able to handle them without using up more addresses in the register space. when you access a register in group 15, first set the page pointer register to the number of the page that contains the register you want. here is how a page is selected: hexa- decimal register number decimal register number function eight-register block decimal (hexadecimal) srp0 #n (or srp1) #n instructions to select a block to provide r0-r7 and r8-r15 respectively f8-ff 248-255 paged registers 31 (1f) srp0 or srp1 #31 f0-f7 240-247 paged registers 30 (1e) srp0 or srp1 #30 e8-ef 232-239 system registers 29 (1d) srp0 or srp1 #29 e0-e7 224-231 system registers 28 (1c) srp0 or srp1 #28 d8-df 216-223 general purpose registers 27 (1b) srp0 or srp1 #27 d0-d7 208-215 26 (1a) srp0 or srp1 #26 c8-cf 200-207 25 (19) srp0 or srp1 #25 ... ... ... ... 78-7f 120-127 15 (0f) srp0 or srp1 #15 ... ... ... ... 20-27 32-39 4 srp0 or srp1 #4 18-1f 24-31 3 srp0 or srp1 #3 10-17 16-23 2 srp0 or srp1 #2 08-0f 08-15 1 srp0 or srp1 #1 00-07 00-07 0 srp0 or srp1 #0
22/146 ST9 user guide figure 9 . selecting page registers as with the working registers, if a subroutine or an interrupt routine needs to access a periph- eral that uses paged registers (which is very likely), you must save (or push) the register pointer ppr at the beginning of the routine and restore it on exit. notes: in both assembly and c languages, include files are supplied with symbolic names pre-defined for all the peripherals. these names are unique for each peripheral; however several different names relate to the same register, but in a different page. you must bear in mind that writing for example (in c language): s_isr = 0; /* clear serial peripheral error register */ does not automatically select the proper page; this statement must be preceded by another one that selects the sci page. since no predefined c statement exists for this, a convenient way is to define an assembler statement under the form of a macro that will read nicely in the c source. an example of the correct way to access the sci register is: #define selectpage(page) asm ("spp %0":: "i" (page)) ; /* pseudo function to select a page */ selectpage( sci1_pg ); /* select the serial peripheral page */ s_isr = 0 ; /* clear serial peripheral error register */ 3.1.7 memory management unit like most microcontrollers, the ST9 has a bus for interfacing internal and external memories. this allows you to store both programs and data. a special feature of the ST9 is that it can ad- dress a 4 mbyte single space to address rom, ram, eprom, eeprom, flash. group f paged registers group e system registers r255 r240 r239 r224 r00 groups 0 to d page pointer register (ppr) r234 page 3 ppr loaded using instruction code spp #3.
23/146 ST9 user guide to address the 4 mbytes of memory, the address bus is 22 bits wide. to manage the 22-bit address with 16-bit direct or indirect addressing, the memory mechanism adds extra bits to the 16-bit address and then works with segments (see figure 10 ) or pages (see figure 13 ). the memories are arranged in 64 segments of 64 kbytes for the program and in 256 segments of 16 kbytes for data. a set of special registers is used to extend the 16-bit address. programs use the csr, dma uses the dmasr or isr and interrupts use the isr or csr register to provide the 6 most sig- nificant bits to make a 22-bit address. data uses a set of four registers (dpr0-3) to provide the 8 most significant bits to make a 14-bit address. data can be addressed in the program segment by using special move instructions: lddp , ldpp , ldpd , lddd . it is easier from a hardware point of view to use only one address space for program and data. figure 10 . addressing via csr, isr and dmasr csr dmasr isr 1 2 3 16-bit virtual address 22-bit physical address 6 bits 1 2 3 fetching program instruction data memory accessed in dma fetching interrupt instruction or dma access to program memory mmu registers
24/146 ST9 user guide 3.1.7.1 program segment we can consider this memory as linear since we can jump anywhere in memory space using the special jps, calls and rets instructions. the 6-bit csr register is used to extend the 16-bit address to a 22-bit address by concatena- tion (see figure 10 ). to make a fast branch in the same segment, use the common jp, call and ret instructions. to branch to another segment using a far call, the use of calls saves the current pc value and the csr value (code segment register) in the stack, before loading the pc and the csr registers with the new values. every time the segment changes you have to use the far branch even if you branch from address (n)ffffh to (n+1)0000h. this is because the program doesn ? t manage the 6 high-order bits of the 22-bit program addresses if you don ? t use a far branch to change the csr register value. the script file (described in the development tools chapter) allows you to place all your program modules anywhere in a single segment. the far branch instruction adds only 2 to 4 additional cycles compared to a near branch in- struction. note: in c language, using the small code model (this means only one 64 kbyte segment is used), all calls use local branches. if more than one segment is used, the large code model is required and all calls use far branches even when branching locally. to avoid far calls in the same seg- ment, the segment to be called has to be declared as static if it is not called from another seg- ment. 3.1.7.1.1 segment and offset in assembler mode or c language the offset represents the address in the segment with 16 bits. if the segment and the offset are known, the following syntax is used for the far branches: jps segment,offset ; 6 bits + 16 bits jps symbol ; 22 bits calls segment,offset ; 6 bits + 16 bits calls symbol ; 22 bits calls (r),(rr) ; 6 bits + 16 bits calls (r),(rr) ; 6 bits + 16 bits rets ; 22 bits the assembly tools accept a set of directives which retrieves the elements of a function ad- dress or of a label. the operator seg (stands for segment) allows you to extract the segment number of a label; similarly, the operator sof (stands for segment offset) allows you to extract the offset of a label within its segment.
25/146 ST9 user guide these operators are especially useful when applied to a function or instruction label, although the macro-assembler and assembler do not verify the type of the label. example: ld r0,#seg function ; extract the 6-bit segment ldw rr2,#sof function ; extract the 16-bit offset calls (r0),(rr2) the same functions exist in c language: seg(function); sof(function). 3.1.7.2 interrupt service routine segment one program segment is reserved for storing the interrupt service routines. all the interrupt routines start in this segment. to obtain a 22-bit address, the 16-bit address is concatenated with 6 bits from the isr register (the 6 bits from the isr register are the high-order bits of the address). to offer compatibility with the previous ST9 versions and to have a new powerful address mechanism, you can select ? ST9 ? mode using the emr2 bit in the encsr register. both modes use the concatenation of the isr register value and the 16-bit address as shown in figure 10 to address the interrupt vector. then, in ? ST9 ? mode, only the isr register value is used during the interrupt routine. so it ? s not possible to jump to another segment from the interrupt service routine because the csr reg- ister value is not saved with the flagr value and the current pc value when the interrupt oc- curs. the advantage of ? ST9 ? mode is to reduce stack memory usage and cpu cycles by not saving the csr value (see figure 11 ). this figure shows you the different mechanisms that are used when an interrupt occurs, when a branch or a call is executed during the interrupt routine and when the return from interrupt instruction (reti) is executed.
26/146 ST9 user guide figure 11 . interrupt processing in ?ST9? mode in ? ST9 ? mode, saving the csr value allows you to change its value to branch to another seg- ment. when the interrupt occurs and when the current pc, csr and flagr values are saved, the isr register value is stored in the csr register (see figure 12 ). flag pc msb pc lsb stack 22-bit 6-bit 16-bit 16-bit address of any branch addresses of local branches flag pc msb pc lsb stack 22-bit 6-bit 16-bit flagr register return from interrupt. the current pc value saved in the stack and the csr value are concatenated to make the 22-bit return address. isr csr flag pc msb pc lsb stack pc msb pc lsb only the pc value is saved for a call instruction when an interrupt occurs, the 8-bit ivr address is extended to 22-bits to obtain the address of the (within the same segment as the interrupt service routine, extended to 22-bits as shown interrupt service routine as shown above. using the call instruction) are 16-bit isr interrupt 22-bit 6-bit 8 bits interrupt service routine address isr ivr at ? 0 ? 6-bit 22-bit vector 8-bit above.
27/146 ST9 user guide figure 12 . interrupt processing in ? ST9 ? mode 3.1.7.3 dma segment to address the total 4 mbytes of memory in a dma transaction, the dmasr points to a 64-kbyte segment. since there is no need to have more than one segment at the same time for the transaction, the dma uses a single 64-kbyte segment instead of 4 pages like a data segment (see below). to use the dmasr register, the dp bit in the dma address register (dapr) must be set. if dp is reset, the dma uses the isr register instead of the dmasr reg- ister. csr pc msb pc lsb stack 16-bit 22-bit 6-bit 16-bit 16-bit address of any branch addresses of local and far branches (to any segment) are extended to 22-bits as shown csr pc msb pc lsb stack 22-bit 16-bit flagr register return from interrupt. the current pc value and the csr value saved in the stack are concatenated to make the 22-bit flag csr isr before loading the csr register with the isr value, the csr value is saved in the stack. csr is saved with the current pc value in the stack and the csr register is loaded with the new 6-bit csr flag return address. csr+pc represent the 22-bit current address saved. csr pc msb pc lsb stack flag segment to jump to. csr pc msb pc lsb next segment for a far branch interrupt when an interrupt occurs, the 16-bit interrupt vector is extended to 22-bits as shown above. 22-bit 6-bit 8 bits interrupt service routine address for a far call, the csr value isr ivr at ? 0 ? 6-bit 22-bit vector above. 8-bit
28/146 ST9 user guide 3.1.7.4 data segment data uses the page mechanism to address the 4 mbytes of memory. to authorize data coming from different 64-kbyte segments, a set of 4 data page registers (dpr0 to dpr3) allows you to address 16 kbytes per register (see figure 13 ). the dpr is se- lected with the 2 high-order bits of the 16-bit data address: dpr0: from 0000h to 3fffh (b15-b14=00) dpr1: from 4000h to 7fffh (b15-b14=01) dpr2: from 8000h to bfffh (b15-b14=10) dpr3: from c000h to ffffh (b15-b14=11) after you select the dpr, the 8-bit value of the selected dpr register is used to extend the 14 remaining bits of the address to 22 bits. for example, if dpr0 equals 20h and dpr1 equals 2h, each memory access in the range of 0000h to 3fffh uses the dpr0 page and addresses data from 080000h to 083fffh, and each memory access in the range of 4000h to 7fffh uses the dpr1 page and addresses data from 008000h to 00bfffh (see figure 13 ). for example: 16-bit address = 0010 0101 1010 0101 = 25a5h 0000h < 25a5h < 3fffh dpr0 is selected, so the 6 high-order bits are equal to 20h 22-bit address = 0010 0000 10 0101 1010 0101 dpr0 value, 14 lsb of the 16-bit address = 00 1000 0010 0101 1010 0101 = 0825a5h with this mechanism, if the 16-bit addresses are different only on the 2 highest bits and if all the dpr registers selected with these two bits have the same value, the resulting 22-bit ad- dress will be the same. four pages of 16kbyte of data memory are enough for many applications and allow you to use data from different segments without costing additional cpu cycles. with four dprs, you can access up to 64k (4 x 16k) of data without changing the dpr values. data can be variables stored in ram or constants stored in program rom. the four dpr registers are located in the mmu register page (page 21 of register group f). if you use them frequently, you can relocate them to register group e, by programming bit 5 of the emr2 register (r246 in page 21). this prevents you from having to switch to the mmu register page from another peripheral register page in order to change a dpr register value.
29/146 ST9 user guide figure 13 . addressing via dpr0-3 3.1.7.4.1 accessing the page and the offset in assembler or c language the assembly tools implement a set of operands which allows you to extract the components of a data address. the pag operator (stands for page) extracts the page number of an address; similarly, the pof operator (stands for page offset) extracts the offset of the address within the page. syntax: pag label pof label be careful that directly using the data label and using the pof operator on a data label are not equivalent: the data label gives the 16 bits of the logical label address; the pof operand gives the 14 lowest bits of the label ? s physical or logical address. example: assuming data is mapped at address 0x129876: ldw rr2,#pof data ; rr2 = 0x1876 ldw rr4,#data ; rr4 = 0xd876 (with dpr3=0x4a) remember that you must take care of which data pointer has to be set before accessing a variable. dpr0 dpr1 dpr2 dpr3 00 01 10 11 14 lsb 8 bits 22-bit physical address 2 m s b 16-bit virtual address mmu registers
30/146 ST9 user guide example: assuming that data has been mapped in a page aligned on address 0xc000, this means that dpr3 will be used, therefore the following code is correct: ld dpr3,#pag data ldw rr2,data ld r4,(rr2) in assembly language, it is possible to access data through another dpr: example: still using data at an address aligned with 0xc000, following code is correct: ld dpr2,#pag data ; if data address=0x01c765, dpr2=7 ldw rr2, #(pof data)+0x8000; rr2=0x8765 ; #(pof data) to reset bit 15 and 14 ; and 0x8000 to use dpr2 ld r4,(rr2) ; indirect addressing mode ... ld r4, (pof data)+0x8000 ; direct addressing mode it is important to look at the explicit usage of the immediate addressing mode (#) to get the page number and the offset; it is consistent with the ST9 assembly syntax shown in the fol- lowing example: ldw rr2,#var ld r4,(rr2) ... ld r4, var the same functions exist in c language: pag(data); pof(data);
31/146 ST9 user guide 3.2 stack modes the ST9 allows you to have two separate stacks: a system stack and a user stack. the core uses the system stack in interrupt routines and subroutines to save return addresses, the flag register and the csr depending on option (emr2 register bit enable code segment reg- ister). you can also use it under program control to save data, using the push and pop instruc- tions. the user stack works exactly the same way, using the pushu and popu instructions but only under program control, which means that the user stack is not changed by the system. you may choose to use a separate space for your data, or to store them in the same stack as the return addresses. both stacks can independently be located either in ram or in the register file. you select this using the ssp and usp bits in the moder register (r235) for the system stack and the user stack, respectively. a low bit value selects a ram stack, and a high bit value selects a reg- ister file stack. since the stacks grow towards low addresses, the stack pointers must be initialized to the highest location plus one (3) of the space reserved to it. this location becomes the ? bottom ? of the stack. when the stack is located in the register file, take care that it does not overwrite other data, in particular the registers located in groups 14 (0eh) and 15 (0fh). for this reason it is advisable to set the system stack pointer to the end of group 13 (0dh). the last register of this group being r223, the instruction that sets the stack pointer will be: ld sspr, #224 ; set stack pointer to one above end of group 13 note 1: using two separate stacks in the same kind of storage (memory or register) area is likely to con- sume more space than if a single stack is used. so most of the time, only one stack will hold both return addresses and arguments for functions. you can then use pushu and popu instruc- tions to manipulate data with the convenience of auto incrementing or decrementing the pointer after each access. as an example, refer to the c language start-up files which initialize both the user and system stacks. the following diagram illustrates the two options for locating the stack: in the register file or in memory. (3) the push instruction decrements the stack pointer before writing the data, so this location would never be used if set to the top location.
32/146 ST9 user guide figure 14 . stack location options 3.3 instruction set the ST9 is said to be an 8/16-bit microcontroller. this means that although the size of the in- ternal registers and the width of the data bus are 8 bits, the instruction set includes instructions that handle a pair of registers or a pair of bytes in memory at once. these instructions repre- sent roughly one half of the total instructions, which means that the ST9 can be programmed with the same ease as if it were advertised as a full 16-bit device. this is why it is well suited for c programming, as illustrated in this book. data memory (ram) bottom of stack group e system registers group f paged registers r255 r240 r239 r00 stack pointer low stack pointer high r255 r240 r239 r00 bottom of stack group e system registers group f paged registers stack pointer low stack pointer high stack stack system or user stack in data memory space system or user stack in register space high byte of pointer irrelevant
33/146 ST9 user guide 3.3.1 overview for a complete description of the instruction set, you should refer to the ST9 programming manual. the aim here is to give you an introduction to the ST9 instruction set and highlight some of its best features in terms of power and ease of programming. most instructions of the ST9 exist in both byte and word forms. that is, they can operate on ei- ther 8 (byte) or 16-bits (word). the mnemonics of the word-instructions all end with a ? w ? , as in the following examples: the new powerful instructions added to the ST9 are the calls, rets, jps instructions for far branching to change the program segment and the instructions used for c language appli- cations, link, linku, unlink and unlinku. moreover, all instructions have been optimized compared to previous ST9. 3.3.1.1 load instructions beside the classical load instructions found on most microprocessors, there are four special load instructions for moving data between two locations in memory. one instruction to move data from data segment to data segment; lddd . this instruction al- lows you to post-increment the destination and the source index register at the same time. the ld instruction needs two instructions to do this. an example for moving a block of data would be: ld rr0,#source ld rr2,#destination ; initialisation of the pointers ld r5,#num_loop ; number of elements to move loop: ld r4,(rr0)+ ; transfer of one byte ld (rr2)+,r4 djnz r5,loop the two ld instructions are coded using 6 bytes and executed in 24 cycles. the same program with the lddd instruction: ld rr0,#source ld rr2,#destination ; initialisation of the pointers load add subtract logical and logical or compare push pop ld add sub and or cp push pop ldw addw subw andw orw cpw pushw popw
34/146 ST9 user guide ld r5,#num_loop ; number of elements to move loop: lddd (rr2)+, (rr0)+ ; transfer of one byte djnz r5,loop the lddd instruction is coded using 2 bytes and executed in 14 cycles. here are the four possible data transfers: these four instructions improve the performance of data block moves (frequently used in c programs). as you can see in the table above, the data move can be between data and program seg- ments. here ? s an example of a data move from a data segment using the dpr register to a program segment using the csr register: ld rr0,#source ld rr2,#destination ; initialisation of the pointers ld r5,#num_loop ; number of elements to move loop: ldpd (rr2)+, (rr0)+ ; transfer of one byte djnz r5,loop the data load with rr0 comes from the data segment selected by one of the four dpr register values depending on the rr0 value and then are stored in the program segment selected by the csr register value. (please refer to the mmu section 3.1.7 for an explanation of data and program segments). 3.3.1.2 test under mask these instructions, tm and tmw, perform a logical (bitwise) and between the two operands, but do not store the result. they only set the z and s bits of the flag register for a later condi- tional jump on zero or sign. the mask is a value in which the bits that are set to 1 select the corresponding bits of the value to be tested for non-zero. as an example, in the following in- struction: tm value, mask instruction moves data from... ...to lddd data segment (uses the dpr0-dpr3 registers) data segment ldpp program segment (uses the csr register) program segment lddp program segment data segment ldpd data segment program segment
35/146 ST9 user guide if the mask is a byte whose binary value is 11000000, only the left-most two bits of the un- known value will be tested, and a later branch if zero will be taken or not according only to these bits. as shown below, the same mask is used for two values that differ only by one bit: two more instructions, tcm and tcmw, work essentially the same way, but they take the com- plement of the value to be tested before anding it with the mask, as follows: tcm value, mask the same two cases will provide the following results: the jump would be taken if the byte to be tested had two 1 ? s in its most significant two bits, for example 11110101. 3.3.1.3 push and pop since there are two stacks, there are two kinds of push and pop instructions. the mnemonics push, pushw, pop and popw act on the system stack, which can be either in the register space or in the memory space. the mnemonics pushu, pushuw, popu and popuw act on the user stack, that can also be either in the register space or the memory space. the stack pointer used in each case is the sspr or the uspr register pair respectively. the stack pointers are always decremented before writing on pushing, and they are incremented after reading on popping. thus the stack pointer always points to the last byte written. this is worth knowing if you need to manipulate the stack contents. the operands to be pushed can be a register, a pair of registers or an immediate value: 000110101 byte to be tested 1 0110101 110000000 mask used for testing 1 1000000 000000000 result of the logical and operation 1 0000000 jump taken result of the ? jump if zero ? jump not taken 000110101 byte to be tested 1 0110101 111001010 complement of the byte to be tested 0 1001010 110000000 mask used for testing 1 1000000 110000000 result of the logical and operation 0 1000000 jump not taken result of the ? jump if zero ? jump not taken
36/146 ST9 user guide push r6 push (r120) push #80 pushw rr100 pushw #1500 pushing an immediate value is especially useful when you are programming in c. a special push instruction is push effective address. this instruction does not push the data itself, but the memory address of the data. for example: pea 5(rr2) this takes the contents of rr2, adds 5 and pushes the result onto the stack. this is widely used in c programming. 3.3.1.4 multiply and divide the multiply instruction takes two byte operands and provides a word result. all numbers are treated as unsigned numbers (operands 0 to 255, result 0 to 65535). though both operands are bytes, the first one must address a word to receive the result. the first operand should then reside in the low byte of the word, and the high byte, not used in the operation, will be overwritten. the flag register is affected but the state of the flags after the operation is mean- ingless. to multiply a signed number (operands -128 to 127) by an unsigned number (operands 0 to 255) with a result in the range of -32768 to 32767, refer to the example given below: ld r1,#signed_data ld r4,#unsigned_data btjt r1.7,neg mul rr0,r4 ; rr0 = r1*r4, with r1 value a positive signed ; number jp end neg: mul rr0,r4 ; rr0 = r1*r4, with r1 value a negative signed ; number sub r0,r4 ; rr0=rr0-100h*r4 end with the signed operand equal to 226=0e2h (means -30 for signed data) and the second un- signed operand equal to 0fh (+15) the result will be -450 (0fe3eh).
37/146 ST9 user guide this ? eight bits signed by eight bits unsigned ? multiplication with a ? sixteen bits signed ? result takes a maximum of 36 cycles. there are two divide instructions. the div instruction divides a word by a byte, and returns the quotient and the remainder as the low and the high bytes of the destination respectively. for example: ldw rr0,#31184 ; rr0=#31184 ld r2,#201 ; r2=#201 div rr0,r2 ; rr0=1d9bh, 1dh=#29 and 9bh=#155 this puts the value 155 in r1 (the quotient) and the value 29 (the remainder) in r0, and r2 still contains 201. if the divider is greater than the dividend, nothing is done. if the divisor is zero, a trap is trig- gered that acts like an interrupt request, and uses the vector at locations 2 and 3 in program memory. it is up to you to write the appropriate code to handle this trap. finally, the numbers to be divided should be such that the quotient be less than 256, that is, can be stored in a single byte. otherwise, the results are undefined. the usable result is only the data stored in r1 which is 155 (for the previous example), the re- mainder must be divided by the divisor (201) to give more precision (16-bits precision). ldw rr0,#31184 ; rr0=#31184 ld r2,#201 ; r2=#201 div rr0,r2 ; rr0=1d9bh, 1dh=#29 the remainder and ; 9bh=#155 the quotient ld r4,r1 ; r4=9bh=#155 clr r1 ; rr0=1d00h div rr0,r2 ; rr0=0bc24h, 0bch=#188 the remainder and ; 24h=#36 the quotient ld r0,r4 ; rr0=09b24h, 09b24h means in fix-point ; with the point in the 16-bits middle ; 09b24h=155.140625 instead of ; #31184/#201=155.1442786 in the best case, the number of cycles required to divide a word by a byte with 16-bits preci- sion is 80 cycles. this program has to manage overflow and divide by zero functions in order to be able to be used. the divws instruction performs one of the sixteen partial divides required to divide a double word by a word, so you need to write a subroutine to perform the division completely. an ex- ample subroutine is given in the ST9 programming manual.
38/146 ST9 user guide 3.3.1.5 bit operations microcontrollers are often used for controlling inputs and outputs on a single-bit basis, in order to read the state of a contact, switch a relay on or off, etc. because of this and because the data is stored in bytes, instructions for bitwise manipulation of data are welcome. the ST9 provides instructions to load, and, or, exor, set, clear, complement and test single bits. these are bld, band, bor, bxor, bset, bres, bcpl, btset. to designate a single bit in a byte, the notation .n is used. for example, r0.3 means bit 3 of r0. here are examples of bit manipulation instructions: bld r0.2, r6.4 ; bit 4 of r6 copied to bit 2 of r0 bld r0.3, !r6.0 ; complement of bit 0 of r6 copied to bit 3 of r0 band r0.2, r0.3 ; r0.2 contains now (r6.4) and not (r6.0) bor r0.2, r2.7 bset r0.0 ; bit 0 or r0 set to 1 bcpl r0.1; bit 1 of r0 is complemented all the above instructions act on single working registers. if the source operand is preceded by ? ! ? , the complement of the source bit is used. to test a bit, to condition a later jump, we have already described the tm and tcm instructions. there is another instruction, btset, that can act on either a single or a double working register, and that sets the z bit of the flagr register if the designated bit is zero. after which, the bit is set to one. you can use this instruction in an interrupt service routine to test for a request and acknowledge it in a single instruction. warning. don ? t use the bit manipulation instructions directly on bidirectional ports. to avoid unwanted modifications to the port output register contents, use a copy of the port register, then transfer the result with a load instruction to the i/o port. (refer to the input/output bit configuration section in the device datasheet for more details.) 3.3.1.6 test and jump the btjf and btjt instructions test if a bit is set or cleared respectively and branch to another program location if true. for example: btjt r1.5,lampon bset r1.5 ; switch lamp on lampon: ... ; continuation of the program two instructions are well-suited for implementing lookup tables. these are cpjfi and cpjti. they compare a byte in a register with a byte pointed to by a register pair, and increment the pointer
39/146 ST9 user guide if the condition is not met. if the condition is met, the pointer is not incremented and the branch is taken. example: ; find the position of a letter in a text. message:.ascii "this is a trial" ld rr0,#message ; where to search ld r2,#'t' ; the character to search for search: cpjfi r2,(rr0),search ; this is the search loop ... ; here rr0 points to the 11th character of message ... ; continuation 3.3.1.7 far branch as explained in section 3.1.7 , the 4-mbyte memory is a segmented memory. it is not possible to reach another segment with the common call, ret and jp instructions because they do not manage the csr (code segment register) register. this is managed by the three new calls, rets and jps instructions. only 2 to 4 cycles are added to the common instructions. 3.3.1.8 optimized c instructions in c functions when a function is called, the compiler needs to push the variables in the user/ system stacks and to keep the return address location of the function inside the stack. therefore, a frame pointer is used, and 2 pieces of code named prologue and epilogue need to be added by the c compiler at the beginning and at the end of the function respectively. the link and unlink instructions (linku, unlinku to use the user stack) are used to re- duce the code overhead generated by the compiler inside the function. these instructions are automatically added by the c compiler instead of prologue and epilogue (if option -mlink is specified). the number of cycles gained by using these instructions is about 34 to 42 cycles and 8 bytes per called function.
40/146 ST9 user guide 3.3.2 advantages when using c language the ST9 has been designed with high-level languages in mind. in particular, the instructions described above are of special interest to c programmers. first, as a structured language, c typically uses the stack to pass arguments to functions, re- turn values from functions, and store the local variables of the functions. an instruction such as: pushw #1500 pushes a constant integer value as the constant argument of a function. this is used in the fol- lowing example: /* define a function that has a single argument of int type */ void myfunction ( int param ) ; { /* body of the function */ } void main ( void ) ; { /* some code ... */ myfunction ( 1500 ) ;/* invoke this function with a constant argument */ /* more code ... */ } since c makes heavy use of pointers, the instruction: pea 4(rr2) pushes the address of the 5th byte of a structure. for example: /* define a structured type */ struct smystruct { int n1 ; int n2 ; char c1 ; } ; struct smystruct mystruct ;/* create a variable of the above defined type */
41/146 ST9 user guide /* define a function that has a single argument of type pointer to character */ void myfunc ( char * arg ) ; { /* body of the function */ } void main ( void ) ; { /* some code */ /* invoke the function with the address of the character element of the structure */ myfunc ( &mystruct.c1 ) ;/* &mystruct.c1 = 4(rr2) if rr2 contains the address of mystruct */ /* more code */ } the lddd, ldpp, lddp, ldpd instructions are used for block copies such as assignments of struc- tures, etc. powerful addressing modes such as indirect, indirect with increment or decrement and in- dexed shorten the code needed to access data even in structures or arrays. they also facili- tate access to local variables created on the stack on entering functions. working registers that benefit from the most powerful instructions and addressing modes are heavily used by the compiler. in fact, the gnu9 compiler does not always translate the source code as suggested above. there are optimization schemes that save execution time and/or memory by judi- ciously allocating the working registers, so that in many cases arguments are not pushed to the stack, but merely to an available working register. 3.4 interrupts the interrupt system of the ST9 is very powerful, and, in consequence, requires some thor- ough study to get the most out of it. however, it is worth learning since it allows you to build very efficient programs with excellent interrupt response times. the ST9 interrupt system works the same as that of any microcontroller, except for two points that call for special attention: the vector mechanism and the priority mechanism (4) . (4) device datasheet; interrupts 4.
42/146 ST9 user guide 3.4.1 interrupt vectors unlike most microcontrollers, the ST9 uses a two-level indirect interrupt vector system. this means that each peripheral able to generate interrupt requests has a vector register that points to a location in program memory (the vector array). this location contains the address of the start of the interrupt service routine. this allows each peripheral to generate several dif- ferent interrupt requests: the peripheral vector register points to an array of pointers to rou- tines, each routine responding to a different interrupt cause. all pointers to interrupt pro- cessing routines, except the reset, must be located in the first 256 bytes of the interrupt ser- vice routine (isr) segment (one of the 64 code segments). the trap for divide by zero with the associated far call to the interrupt service routine has to be repeated in all memory seg- ments containing programs that perform division. code may also reside in this 256-byte space, provided that it does not overlap with the interrupt vectors. figure 15 shows the complete mechanism of the 22-bit address construction from the interrupt which provides the interrupt vector register value to the return from interrupt. for each peripheral, the layout of the vector array is specified in the section related to its own interrupt vector register.
43/146 ST9 user guide figure 15 . interrupt vectors as an example, let ? s take the ST92f150 multifunction timer 0. the registers that define the mft0 functions are all contained in pages 9 and 10 of register group 15 (0fh). register 242, called the interrupt vector register (ivr), holds the address of the beginning of the vector array in program memory. the ivr has the following bit layout: 00 0000 00 ffff 01 0000 xx ffff isr 0000 r240 r255 paged registers interrupt vector interrupt service routine address 8-bit memory space interrupt program 6-bit register (ivr) 8-bit 00 22-bit 16-bit isr segment segment 0 22-bit bit d0 of ivr is always 0 since the addresses of the interrupt service routine start at even addresses divide by zero trap isr address of divide by zero trap isr address of reset isr address of repeated at each segment only for the first segment 00 0002 isr 0002 at the end of the interrupt service routine, the iret instruction returns to the program in the segment selected by csr (csr_5 to csr_0) pc from stack 22-bit divide by zero trap (1) if the encsr bit of emr2 is set (enable code segment register), the csr is saved in the stack and then csr from stack isr csr (2) loaded by the isr. if it ? s reset, the csr is not saved and only the isr is used. (2) if the encsr is set, the csr is reloaded with the value saved in the stack when the interrupt occurs. if it ? s reset, csr is used instead of isr when the reti instruction occurs (return from interrupt). isr or csr (1)
44/146 ST9 user guide t0_ivr (r242 page 9) where v4-v0 (fixed by software) are the high bits of the low byte address memory where the vector for the first interrupt cause is located. since there are three different interrupt causes, and the address of each interrupt service routine occupies two bytes, the ivr must be loaded with an address between 8 and 250 that is a multiple of 8 (i.e. the lower three bits are zero). the layout above shows two bits w1 and w0 (fixed by hardware), and a third bit that is per- manently set to zero. the two w1-w0 bits code four different possible interrupt causes, as in the following table: when an interrupt occurs, the resulting value is an address that is the value written in ivr (here 40h), plus the value coded by the cause (if the cause is a capture event, w1-w0 are 10, thus the value is 4). this gives an even number, since the least significant bit is zero, as follows: so ivr points to address xx 0044h (with xx the isr segment number), which must contain a word that is equal to the address in the isr segment of the interrupt service routine for that cause. an example of the code for setting the ivr is: void configtimer0 ( void ) { /* setting other registers... */ selectpage (t0c_pg) ; t0_ivr = (unsigned char)intreloadvect ;/* array of pointers to service routines in rom */ /* setting other registers, continued... */ } v4 v3 v2 v1 v0 w1 w0 '0' w1 w0 interrupt source 0 0 overflow/ underflow event interrupts 0 1 not available 1 0 capture event interrupts 1 1 compare event interrupts v4 v3 v2 v1 v0 w1 w0 0 01000100
45/146 ST9 user guide figure 16 . interrupt vectors: example with multifunction timer 0 the corresponding source code could be: ; this program uses the 3 interrupt possibilities of mft0 ; constants it_mft0_vect = 40h ; vector table .section.text .org 00h ; (default address) .word reset ; reset vector -; if needed divide by zero, nmi vectors - r240 r255 65535 45h isr addre s s on ov f/ unf 47h p a g e 0 9 r242 isr on compare event isr on captur e event isr on ov f/ unf eve nt 46h no t avai l abl e 44h 43h 42h 41h 40h 00h memory (16-bit address space) interrupt vector table the value 40h as the base address of the interrupt vector table is chosen arbitrarily by the programmer interrupt vector register (ivr) contents = 40h isr address on compare event isr address on capture event group f paged registers (8-bit address space)
46/146 ST9 user guide - .org it_mft0_vect .word isr_ovf_unf; isr address on ovf /unf .fill 1,2,0xffff ; does not exist in mft0 interrupt ; skip one vector .word isr_capt ; isr address on capture event .word isr_comp ; isr on compare event - - - ; somewhere in the initialisation code... ;mft0 initialisation mft0_init: spp #t0c_pg ; select mft0 control register page - -; setting of some other registers... - ld t0_ivr, #it_mft0_vect; pointer for the vector table - - -; continuation of the program... a similar scheme applies for all other peripherals, though the number of interrupt causes may vary, and thus the size of the pointer table. note: to summarize, the table of vectors to an interrupt service routine in rom for a given peripheral is itself pointed to by the interrupt vector register of this peripheral that must be set to the prop- er value. this gives you an unusual degree of flexibility: a peripheral may have different interrupt service routines at different times, without the need to add tests at the beginning of the interrupt service routine. let ? s consider for example that we want to transfer a string of data from a pe- ripheral. when the first byte of data comes in, we must initialise some variables to handle the string. then, all subsequent transfers merely copy the data from the peripheral to memory and increment the pointer. switching between these two modes is very easy. initially, the ivr of the peripheral is set to the block of vectors that point to the interrupt service routine that serves the first time. this interrupt service routine changes the value of the ivr to another block of vectors and returns. the next interrupt will be automatically re-routed to the other, lighter, interrupt ser- vice routine. this reduces the execution time of this routine, since we do not need to test wheth- er this is the first time that the interrupt service routine is called or not.
47/146 ST9 user guide 3.4.2 interrupt priorities in any microprocessor-based system, there is a trade-off between the computational power of the main program and the interrupt latency time. expressed simply, the less the main program is disturbed, the sooner it finishes its job. on the other hand, we often need to serve interrupt requests generated by the peripherals as quickly as possible. since this is a trade-off, we need to find a compromise that gives both enough power to the main program while still keeping it as responsive as possible to interrupts. it is likely that we will need to modify this compromise according to the current status of the program. if we define that some interrupt requests are more urgent than others, we can define a priority or a hierarchy of interrupt requests. the main program itself, if given a priority level, should be considered as having the lowest priority (except sometimes when interrupts are undesirable). in most cases, when the main program is running, it can be interrupted by any interrupt re- quest. but once a request is being served, it most likely needs to continue undisturbed, unless a request from a higher priority level occurs. then, the higher priority request is served until completion. the service routine then returns to the lower priority interrupt service routine, that terminates and eventually returns to the main program. in the ST9, this behavior is called nested mode. other types of behavior may be required depending of the kind of processing. for this, the ST9 interrupt system has two boolean parameters to select the way interrupts are handled, which allow four basic choices. the priority mechanism is driven by the current priority level parameter. at a given time, the part of the program being executed runs under a certain level. you can change this cpl by writing a different value in the core ? s central interrupt control register (cicr). you can assign priority level (pl) to each interrupt source. at initialisation time, this value is written in one of the control registers specific to the corresponding peripheral. note: the pl is a three-bit word that ranges from 0 to 7. note that 0 stands for a high priority and 7 for a low priority. these bits belong to one of the configuration registers of each peripheral. when a peripheral requests an interrupt, the built-in interrupt controller compares the priority level of the interrupt request to the current priority level. the interrupt is only acknowledged if its priority level value is strictly less than (higher priority) than the current priority level value. this allows you to filter out interrupt requests according to their degree of importance or of urgency according to the current activity of the program. the non-maskable interrupt input (nmi) is hard wired with a higher priority than any level, and thus is acknowledged immediately in all circumstances. the ST9 offers two modes for managing interrupt priorities: ? concurrent mode ? nested mode
48/146 ST9 user guide the difference between them is explained below. 3.4.2.1 global interrupt enable flag in both modes, when an interrupt request is acknowledged, the interrupt enable (ien) bit is cleared, preventing the interrupt service routine from being interrupted again until it is finished. if required, you may prefer to keep it cleared for the duration of the routine or to set ien at some place in the routine using the ei instruction. in the first case, if an interrupt request of a sufficient priority level is received, it will only be serviced as soon as the service routine cur- rently running returns. in the second case, the same interrupt request is serviced as soon as both it occurs and the ien bit is set. in short, interrupt service routines may be re-interrupted or not, at will. 3.4.2.2 concurrent mode versus nested mode selecting either concurrent mode (automatically chosen on reset) or nested mode changes the way the current priority level is managed. in nested mode, the cpl is automatically set to the priority of the current interrupt service rou- tine, and is reset to the previous value on return. this allows you handle the interrupt request according to priority at all times, since during the execution of the service routine for a given in- terrupt, only those interrupts whose priority is strictly higher than that of the one currently being served will be taken into consideration. then if, as must normally be done, the ien bit is set during the current service routine, it will be interrupted at once if an interrupt request of higher priority occurs. if the ien remains cleared for the whole duration of the service routine, those interrupt requests will be served first after the current routine has returned.
49/146 ST9 user guide figure 17 . example with nested interrupts enabled figure 18 . example with nested interrupts disabled 6 5 4 3 2 1 0 7 priority main program interrupt #2 main program cpl is cpl = 5 cpl = 2 cpl = 5 cpl = 7 ei interrupt #2 has priority level 2 interrupt #5 has priority level 3 interrupt #6 has priority level 6 main program has priority level 7 interrupt #5 interrupt #6 interrupt #5 cpl = 6 interrupt #6 is requested but not served because its priority is lower than the current cpl interrupt #5 is requested interrupt #2 is requested and served (automatically) set to 7 di ei ei ei nested mode: iam bit = ? 1 ? ien is set to ? 1 ? by the programmer (interrupt #5 can be served) level 6 5 4 3 2 1 0 7 priority main program interrupt #2 main program cpl is cpl = 5 cpl = 2 cpl = 7 ei interrupt #2 has priority level 2 interrupt #5 has priority level 3 interrupt #6 has priority level 6 main program has priority level 7 interrupt #6 interrupt #5 cpl = 6 interrupt #6 interrupt #5 is requested interrupt #2 is requested (automatically) set to 7 di nested mode: iam bit = ? 1 ? ien is not set to ? 1 ? by the programmer (interrupt #5 can be served) is requested level
50/146 ST9 user guide in concurrent mode, the cpl is set exclusively by the programmer. you can change it if you need to shift the compromise mentioned above either towards main program efficiency, or to- wards short interrupt latency times. so you can have a high-priority service routine that is re- interrupted by a low-priority interrupt request, if the cpl has been set to a low priority and the ien bit is set. this mode gives you maximum flexibility, but it is the most difficult to use since you must keep track of every combination of interrupt requests to achieve the efficiency you expect from your program. figure 19 . example with concurrent interrupts enabled concurrent mode does not look like a reasonable way to handle interrupts if you enable inter- rupts in your interrupt service routine. it should be thought of as a way to fully control priorities through programming, if nesting priorities cannot meet your processing requirements. for ex- ample, let us consider the case when a timer produces a periodic interrupt that outputs some data on an external digital to analog converter. the requirement is that the new data be output at the very time of the interrupt, so as to reduce the jitter (or parasitic frequency modulation) that would compromise the spectral purity. then, once the data is output, the interrupt service routine does some processing to make or get the data for the next interrupt. the latter part of the processing is much less critical in terms of execution time, provided it is finished before the next timer interrupt. using concurrent mode, you can assign that interrupt the highest priority so that it will be served immediately, then re-enable the interrupts and, if needed, give it a pri- 7 6 5 4 3 2 1 0 main program main interrupt #5 interrupt #2 interrupt #6 interrupt #2 interrupt #5 interrupt #5 is requested interrupt #2 and #6 are requested. the interrupt #2 is served first because it ? s priority is higher than the interrupt #6 cpl is set to 7 cpl=7 cpl=7 cpl=7 cpl=7 cpl=7 cpl=7 ei ei interrupt #4 cpl=7 ei interrupt #4 cpl=7 interrupt #4 is requested interrupt #4 is served first because it ? s priority is higher than the interrupt #6 interrupt #2 has priority level 2 interrupt #4 has priority level 4 interrupt #5 has priority level 5 interrupt #6 has priority level 6 main prog has priority level 7
51/146 ST9 user guide ority level as appropriate. the service routine will then allow other interrupts to gain control, at the expense of delaying its own completion. note 1: in practice, concurrent mode does not differ much from nested mode if the interrupts are not re- enabled during an interrupt service routine. concurrent interrupts disabled looks like nested in- terrupt disabled with the difference that the cpl is changed only by software when necessary. the interrupt requests pending while the interrupt service routine is executing, will only be ser- viced after the current service routine returns. note 2: an interrupt with priority level 7 will never be served. 3.4.3 external interrupt unit this is a functional block that can receive interrupt requests from up to eight external pins, and also from some internal devices such as the watchdog timer, the serial peripheral interface, etc. it is used to select the active edge for pin or device, and define the priority for each of the four pairs. in addition, an nmi pin can be programmed as being maskable or non-maskable. it is maskable on reset, and once set to non-maskable, it cannot again be set to maskable until the next reset. this works as explained below. 3.4.3.1 maskable external interrupt pins these are eight external inputs you can set individually to rising-edge or falling-edge sensitive, and masked. you assign priorities by pairs, making four groups with different priorities. within each group, the two interrupt requests have two successive priorities. for example, if you set group c to priority 2, the int4 input will have priority 2 and int5 will have priority 3 (which is lower).
52/146 ST9 user guide the simplified block diagram is the following: figure 20 . external interrupts simplified block diagram 3.4.3.2 top-level interrupt the top level interrupt can have two sources: either the nmi pin, or the watchdog end-of- count (5) . this interrupt level has a special feature that allows you to mask it like any other in- terrupt, or to make it a real non-maskable interrupt. for this, the tlnm bit (see figure 21 ) can remove the effect of the mask. once set, it cannot be reset, thus preventing this interrupt from (5) see section 4.3 on the watchdog timer. 3 3 external interrupt pin (int0 to int7) edge trigger event selection: one bit of eitr internal/external source selection one bit of eipr pending bit one bit of eimr external interrupt priority level current priority level (cpl) interrupt to the core bit ien of cicr interrupt enable only for: a0: int0 or wdt interrupt b0 int2 or spi interrupt internal interrupt priority comparator (device dependent) a detailed block diagram is provided in section 7 mask bit
53/146 ST9 user guide being accidentally masked even in the case of a program failure. in any case, the top level interrupt uses the third fixed vector at addresses 4 and 5 in program memory. as the name im- plies, it has a fixed priority that is higher than any other interrupt request. though it does not clear the ien bit when acknowledged, unlike all other interrupt requests, its service routine cannot be interrupted by any cause, including the top level interrupt itself. the simplified block diagram is the following: figure 21 . top-level interrupt simplified block diagram nmi pin edge trigger event selection: one bit of eivr watchdog/nmi source selection: one bit of cicr pending bit one bit of nicr top level interrupt to the core watchdog timer end of count one bit of eivr top level not maskable interrupt bit interrupt enable: two bits of cicr a detailed block diagram is provided in section 7
54/146 ST9 user guide 3.4.3.3 external interrupt vectors there are eight external interrupt causes. they are each connected to an external input that is the alternate function of an i/o port. some of these are shared with other causes in an exclu- sive manner, i.e., the int0 pin is multiplexed with the watchdog/timer interrupt request, and the int5 pin is multiplexed with the serial peripheral interface interrupt request (on the ST92f150). each cause is associated with a separate vector in program memory. all vectors are contiguous, generating an array of 8 vectors starting with the int0 vector, and ending with the int7 vector. this array may be freely located in program memory between addresses 8 to 240 (0f0h) in program memory. these interrupt causes are grouped by pairs, and are given new names inside the interrupt controller, as shown in the following table: you can independently assign a priority to each pair (a, b, c, d), with levels that are multiple of two, i.e. you can set them to priority levels 0, 2, 4, or 6. in each pair, the cause bearing the figure zero assumes this priority, and the cause bearing the figure 1 assumes the next level above. for example, if you assign level 4 to pair c, this means that intc0 will have level 4 and intc1 level 5. you set this in register eiplr (r245 page 0), where each group of two bits gives the level of the corresponding interrupt cause. the interrupt vectoring is summarized in the table below: interrupt source interrupt cause int 0 int a0 int 1 int a1 int 2 int b0 int 3 int b1 int 4 int c0 int 5 int c1 int 6 int d0 int 7 int d1
55/146 ST9 user guide figure 22 . external interrupt vectors 0 7 lsb of the vector table address for the 8 external interrupts (hardware fixed) msb of the for the (software fixed) eivr (r246, page 0) external interrupt vector register isr address for intd1 isr address for intb0 isr address for inta1 isr address for inta0 vector table: (addresses less than ffh) 8 external interrupts vector table address v7 v6 v5 v4 tltev tlis iaos ewen v7 v6 v5 v4 1111b 1110b 0111b 0110b 0011b 0010b 0001b 0000b lo hi lo hi lo hi lo hi
56/146 ST9 user guide 3.5 dma controller 3.5.1 overview one of the most important advantages of the ST9 is its ability to handle input/output data flows without using core instruction cycles. this is made possible by the built-in dma controller. once properly initialized, it allows peripherals to exchange data either with memory or the reg- ister file, with no more use of the core resources than the stolen memory cycles strictly needed to transfer the data. to see how much faster dma is than the simplest interrupt service routine, let us compare the execution times. let us assume that the data comes from the serial port. the simplest interrupt routine is the following: getonebyte:; interrupt latency: 22 cycles push ppr ; save current page 8 pushw rr0 ; save rr0 10 spp #sci_pg ; change register page 4 ldw rr0, pointer ; get pointer 12 ld (rr0)+, s_rxbr ; move data 12 ldw pointer, rr0 ; store pointer 14 popw rr0 ; restore rr0 10 pop ppr ; restore current page 8 iret ; return 16 ; ------------------------------------------- ; total: 116 with an internal clock of 24 mhz, this corresponds to an execution time of 4.8364 s. in con- trast, the dma cycle time for the transfer of one byte from a register to a register file takes only 8 cycles (16 cycles to the memory), that is 0.33 s. the dma feature saves you from using valuable core processing power for simple tasks like storing an input byte to memory. for ex- ample, if a continuous flow of data is input at 19200 bits per second, the interrupt service rou- tine would consume 1.11% of the total cycles of the core, as compared to the 0.0767% with the dma solution. since the dma is built-in and works with most of the peripherals, it is a good idea to use it even for slow transfers. the dma uses the segment mechanism to address 64 kbytes along the linear 4 mbytes. see section 3.1.7 for more details.
57/146 ST9 user guide 3.5.2 how the dma works the dma consists of a transfer between a memory or register file and a peripheral, in either di- rection. assuming the peripheral is configured to handle externally supplied data or to provide data to external circuits, two steps are needed for a transfer to occur. the transfer must be requested by some event or condition. a mechanism must handle reading the data from one part and writing to the other part. the term dma transfer represents the transfer of a single byte of data. usually, more than one byte is transferred and the transfer occurs in bursts. thus, a third step is involved: a mechanism that counts the transfers and stops them when the count is finished. to the programmer, these mechanisms appear as registers to be properly initialized. the three steps are handled as follows (see figure 23 ). 3.5.2.1 transfer requests the dma transfer is requested in exactly the same way as an interrupt is requested. ac- cording to its type, the peripheral concerned sends a request based on an external event such as a character received or transmitted by the serial channel interface. you configure this in the registers belonging to the peripheral involved. special bits in the registers indicate that the peripheral ready status, instead of requesting an interrupt, requests a dma transfer. 3.5.2.2 transfer execution a dma transfer can involve a memory location or a register in the register file. in any case, the transfer requires an address and a counter. this address and counter are stored in registers which you can define anywhere in the register file. the address register value is automatically incremented after each transfer and the counter register value is decremented so that the next transfer will involve the next address and this mechanism will continue until the counter is equal to 0. depending on whether the transfer addresses memory or the register file, there are two cases. if the transfer addresses the register file, the address register and the counter register are single registers (a byte is enough to address 256 registers). the address of this address reg- ister is stored in one of the peripheral's registers, named dcpr. the low bit (rm) of this reg- ister is set to zero indicating that the register file is involved in the transfer. the address reg- ister must have an even address to address the dma address, the next register storing the dma transaction counter. if the transfer addresses the memory, the registers that hold the address and the counter must be two double registers. in this case, the dma address is pointed by the dapr pointer register and the dma transaction counter is pointed by the dcpr pointer register. the low bit of the
58/146 ST9 user guide dapr indicates whether the memory segment is pointed by dmasr or isr (see section 3.1.7 ). the dma address and the dma transaction counter are not necessarily consecutive. 3.5.2.3 transfer termination a burst terminates when the count of transfers reaches a predefined value. to set this up, you set a counter register in the register file that holds the count of transfers to execute at the start of a burst. each transfer decrements it, and the dma mechanism is stopped when the counter reaches zero. the way dma controller terminates the transfer differs from one peripheral to another, but typ- ically it consists of resetting the bit in the configuration register that tells the peripheral to issue dma requests instead of interrupt requests. then, on the last transfer, when the transfer counter reaches zero, it toggles the dma/interrupt request bit so that the peripheral issues an interrupt request again. if this request is unmasked, you should vector it to an interrupt service routine that handles the dma termination. to summarise: for register transfers, the dcpr of the peripheral points to a user-defined pair of registers that holds the address and the count. register dapr is unused. for memory transfers, the dapr points to the user-defined register pair that holds the address. the dcpr register points to the user-defined register pair that holds the count. some peripherals, such as the multifunction timer, even have a double pair of dapr/dcpr registers. only one pair is used at a time. in so-called swap mode, this allows the timer to use one data buffer for output and another buffer for input. the pair of registers used is automati- cally changed when one transfer burst terminates, allowing a continuous data flow between the program and the peripheral, with minimum data handling overhead. in addition, the mft has 16-bit registers. transfers imply two byte transfers for each register. this is ensured by a mechanism that gives the dma the highest priority as soon as the first byte is transferring. this guarantees that the second byte will also be transferred in the shortest delay, even if other dma requests become pending while the transfer is in progress.
59/146 ST9 user guide figure 23 . dma data transfer peripheral data peripheral register file register file address counter 0 df start address current counter value decrease after each transfer current address register file or memory
60/146 ST9 user guide 3.6 reset and clock control unit (rccu) the rccu is composed of the clock control unit ( ccu ) and the reset and stop manager. 3.6.1 clock control unit the ccu generates the peripheral clock intclk and the cpu clock cpuclk . it is a useful clock generator with low power function and low external frequency oscillator to reduce elec- tromagnetic emissions. the diagram can be reduced as in figure 24 . figure 24 . ccu simplified block diagram the ccu is composed of 5 main blocks: block comments 1 quartz oscillator gives the main frequency generator. the frequency is in the range of 3 to 5 mhz. 2 external clock for very low power consumption with a very low frequency. 3 the clock multiplier can reduce or increase the input frequency by using prescaler and pll.the increase is for the normal use and the decrease for low power consumption. 4 the selector aims the clock coming from the clock multiplier for normal or low power use or aims the clock ck_af for a very low power consumption. 5 the prescaler is used also for low power consumption. the intclk is not change giving a high frequency to the internal peripheral. this allows the user to slow down program execution during non processor intensive routines. quartz oscillator ck_af source clock multiplier [ 1/32 to 14 ] prescaler cpuclk intclk 1 2 3 4 5
61/146 ST9 user guide 3.6.1.1 clock multiplier the clock multiplier is a part of the figure 26 . the advantage of the clock multiplier is that it can produce a variable clock frequency de- pending on the needs of the cpu. since the input clock to the pll circuit requires a 50% duty cycle for correct operation, the di- vide by two should be enabled (div2 bit of moder register set) if the pll is enabled. it is nec- essary when a crystal oscillator is used, or when the external clock generator does not provide a 50% duty cycle. in practice, the divide-by-two is virtually always used in order to ensure a 50% duty cycle signal to the pll multiplier circuit. the clock multiplier output is one of the clock2, clock2/16 or clock2*pllmul/(dx+1) (pllmul is the pll multiplier coefficient) frequencies. the two frequencies clock2 and clock2/16 are for low power consumption or reduce power consumption, depending on the wait for interrupt instruction (refer to the flow chart figure 25 ). the pll has four clock multiplier factors (6,8,10 and 14) controlled by the two bits mx0 and mx1 in the pllconf register. the clock divider is controlled by three bits dx0:2 in the pllconf register for seven rates which are 1/(dx+1). setting dx2:0=7 turns off the pll to reduce consumption. when you switch on the pll, you have to allow a delay for the pll to lock.
62/146 ST9 user guide figure 25 . intclk and cpuclk flow chart wfi lpowfi==0 yes no no yes previous wfi_cksel==0 yes no ck_af yes no present clock2/16 clock2/16 ck_af instruction xt_div16==0 yes no clock2/16 (pll off) csu_cksel=0 pll-clock clock2 (pll off) low power reduced power consumption slow mode reduced power consumption fast mode cpuclk stopped cpuclk=intclk/n intclk= pll is off ckaf_sel=0 ckaf_st=0 ckaf_sel=1 ckaf_st=1 csu_cksel=0 csu_cksel=0 clock csu_cksel==0 yes no clock2 (pll on) dx2:0==7 no yes dx2:0==7 yes no ckaf_sel==0 yes no ck_af no yes present ck_af
63/146 ST9 user guide figure 26 . clock control unit programming 3.6.1.2 ck_af source when you execute a wait for interrupt (wfi) instruction using the clock multiplier with output clock clock2/16, the power is put in low power mode. to reduce this power further you have the possibility of slowing down the intclk frequency by using an external clock source ck_af. the ck_af clock will be selected if the wfi_cksel bit in the clkctl register is set and if ck_af is present. the ck_af source can also be used in run mode (no wfi) to reduce power consumption if ckaf_sel is set and ck_af is present. quartz pll ck_af 1/16 x 1/2 div2 ckaf_sel 1/n oscillator mx(1:0) 0 1 0 1 0 1 source ckaf_st csu_cksel 6/8/10/14 1 0 xt_div16 dx(2:0) clock2 clock1 (moder) (clk_flag) (clkctl) (pllconf) (clk_flag) ck_af intclk to peripherals and cpu clock prescaler xtstop (clk_flag) wait for interrupt and low power modes: lpowfi (clkctl) selects low power operation automatically on entering wfi mode. wfi_cksel (clkctl) selects the ck_af clock automatically, if present, on entering wfi mode. xtstop (clk_flag) automatically stops the xtal oscillator when the ck_af clock is present and selected. clock multiplier
64/146 ST9 user guide 3.6.1.3 low power with frequency slow down when the pll has been frozen by a wfi instruction you need a delay after the interrupt to wait for the pll to lock. to avoid this delay but not to lose the low power consumption, you have two choices which are: ? to use a wfi instruction with lpowfi reset and initialize intclk to clock2 with xt_div16 bit set (csu_cksel register). when the wfi occurs, cpuclk is stopped and intclk doesn ? t change. ? to not use the wfi instruction. set xt_div16 bit of csu_cksel register. initialize dx2:0 of pllconf to 6 to divide the pll output clock by 7 which is the maximum. initialize the cpuclk clock prescaler to 7 to divide intclk by 8. 3.6.2 reset and stop manager reset normally means restarting from the beginning with everything initialized. however sometimes it ? s necessary to know the context of the ST9 before the reset and if it was an ex- ternal or internal reset. two bits, softres and wdgres in the clk_flag register indi- cate the previous context. table 3. shows the three cases to manage. table 3. three types of reset these bits are read-only and change with each reset. reset type softres bit wdgres bit meaning external reset 0 0 high to low level on reset pin. watchdog r eset 0 1 the watchdog timer is activated and the timer has reached 0. software reset 1 0 the halt instruction is executed, waiting for an external reset to restart (if the sresen bit in the clkctl register is set).
65/146 ST9 user guide 4 using the on-chip peripherals this chapter introduces the main peripherals of the ST9 family. each variant includes none, one or several peripherals of each type. this allows you to select the variant that best fits your requirements. for high-volume markets, you can order custom versions with exactly the type and number of peripherals required, including the relatively exotic ones not described here but available on request, such as videotext decoders etc. 4.1 programming the core and peripherals in addition to describing how each peripheral works, we give examples of the code needed to use them in several configurations. this code is available on the companion software. you can experiment with the original code or modify it to do the functions you require. configuring and using the core and the peripherals involves a considerable amount of bit ma- nipulation in the registers. many variables that drive microcontroller states are boolean values. to reduce the use of addressable space in registers, bits have been logically grouped in bytes, so the majority of the control registers have their eight bits fully used. to properly program these registers, you need to track the exact position of each bit in each register. you can do this by referring systematically to the appropriate data sheet, and com- menting the source text so that it can be easily read and understood later. see the following example: ld r235,#11100000b ; r235 is register moder ; |||||||+-- himp : no foreign access to bus ; ||||||+--- brqen : no foreign access to bus ; |||+++---- prs2,1,0 : processor at full speed ; ||+------- div2 : crystal frequency divided by 2 ; |+-------- usp : user stack pointer in registers ; +--------- ssp : system stack pointer in registers spp #0 ; spi page ld r254,#10000001b ; |||||||+-- spr0 : spr1, spr0 = 01: clock divided by 16 ; ||||||+--- spr1 : ; |||||+---- cpha : input sampled on rising edge ; ||||+----- cpol : rest level of serial clock = 0 ; |||+------ busy : set to ready ; ||+------- arb : no i2c arbitration ; |+-------- bms : spi used as a shift register (not i2c) ; +--------- spen : spi enabled
66/146 ST9 user guide this style has the advantage of clarity. however, there is still a problem that it does not ad- dress: the variety of the different products of the ST9 family. the different products available in the ST9 family are very diverse and as a result it is not al- ways the case for all products that a given function is performed by the same bit of the same register. the location of a register in one peripheral may be different in another. to avoid this problem, the gnu9 programming tool chain provides a set of include files that define the phys- ical location of every bit and register, by their symbolic name. these files correspond to the appropriate variant of the ST9. using them guarantees that switching to another member of the family will not need more than changing the include statement at the beginning of the source text. the same example as above, using the predefined symbols reads as follows: .include "system.inc" ; system register ld moder,#mom_sspm+mom_uspm+mom_div2m; both stacks in ;registers, clock divided by 2 spp #spi_pg ;spi page ld spicr,#spm_spen+spm_sp_16 ; enable spi,1st clock ; configuration, clock/16 this notation is more compact, and is independent of changes either between variants in the same family, or by changes made globally to the family in the future. this writing style is rec- ommended for this reason. 4.2 parallel i/o the parallel input-outputs have a basically very straightforward functionality. once initialized, they appear as a register that can be written or read. however in many cases, direct byte-wide input-output is not sufficient. bit-oriented i/o is often what is used in microcontroller systems. a powerful feature of the ST9 is that you can address the eight bits of each port individually. the ST9, like most microcontrollers also provides the external pins of the other peripherals (timers, uarts, etc.) by diverting some bits from the parallel i/o ports. the ST9 parallel i/o has an additional very flexible feature. you can independently configure each bit as: ? an input with two variants (ttl or cmos levels) ? an output with also two variants (open-drain or push-pull) ? a bi-directional port with either a weak pull-up or an open-drain output side ? an alternate function output (that is, the output pin of an internal peripheral), with also either open-drain or push-pull output driver.
67/146 ST9 user guide ? analog input (see note) note : on the port that accommodates the inputs of the analog to digital converter, there is a special feature. in all other peripherals that require an input, you only need to configure the correspond- ing pin as an input. however, when using the adc you can put the input pins to any voltage level from ground to vcc. this is normally badly handled by standard logic gates that dissipate con- siderable power when the voltage reaches the limit range. to avoid this, the port that provides the input pins of the adc has a special alternate function mode. unlike the other ports it is used for input. this mode disconnects the input buffer from the pin and shorts the buffer input to the ground. the output buffer is put in high-impedance mode. the pin is permanently connected to the input of the adc, thus allowing its voltage to be read at any time. to handle all these capabilities, each port requires three configuration registers, pxc1, pxc2 and pxc3, where x is the port number. once configured, a port exchanges data with the core through the pxdr data register. the configuration registers are placed in various pages of the register group 15, as well as the data registers, except for the first six ports. these six belong to the system register group (group 14) for easy access. some ports also include dma capability, configurable to work with the multi-function timer.
68/146 ST9 user guide 4.3 standard and watchdog timers you can use this timer both as a regular timer and as a watchdog timer. 4.3.1 description the block diagram of the watchdog timer is the following: figure 27 . watchdog timer simplified block diagram in counter/timer mode, the wdt can count pulses coming either from an input pin (wdin; in the ST92f150, alternate function of p5.3) or from the internal clock divided by 4. when the in- ternal clock is used, the external pin, if enabled, can either gate the clock, start the counter, or wdin pin input modes and clock control logic prescaler (8-bit) 16-bit downcounter output control logic reset and interrupt control logic reset and interrupt request to the core intclk/4 3 bits of wdtcr 2 bits of wdtcr 3 bits of wdtcr 1 bit of wcr wdout pin int0 pin nmi pin 2 bits of eivr a detailed block diagram is provided in section 7
69/146 ST9 user guide reload it with its initial value. you select these modes using three bits in the wdt control reg- ister, as follows: 4.3.1.1 event counter mode the counter value is decremented at each falling edge on the wdtin pin if st_sp is high (bit 7 of wdtcr). figure 28 . timer in event counter mode 4.3.1.2 gated input mode the counter value is decremented by wdtclk (intclk / 4) if the wdtin pin and st_sp are high. figure 29 . timer in gated input mode inen inmd1 inmd2 mode 1 0 0 event counter mode 1 0 1 gated mode 1 1 1 retriggerable input mode 1 1 0 triggerable input mode 0 x x input section disabled. internal clock selected. wdtin pin st_sp counter value wdtin pin st_sp counter value
70/146 ST9 user guide 4.3.1.3 retriggerable input mode the counter value is decremented by wdtclk (intclk / 4) if st_sp is high. the initial value is reloaded either at the rising edge of st_sp or at each falling edge of the wdtin pin if st_sp is high. figure 30 . timer in retriggerable input mode 4.3.1.4 triggerable input mode the counter value is decremented by wdtclk (intclk / 4) if st_sp is high and falling edge of wdtin occurs. the initial value is reloaded at the first falling edge of the wdtin pin if st_sp is high . figure 31 . timer in triggerable input mode initial value wdtin pin st_sp counter value counter value initial value st_sp wdtin pin
71/146 ST9 user guide 4.3.1.5 single/continuous mode on counter underflow (end of count), the counter is always reloaded with the value of the latch that is actually accessed when writing to the wdthr and wdtlr register pair. the counter has two modes: single-shot or continuous, selected by the s_c bit of wdtcr. in single-shot mode, the end of count also resets the st_sp bit of the wdtcr, which stops the counter after one cycle. in continuous mode on reaching the end of count condition, the counter reloads the constant and restarts. when the st_sp bit is set, the contents of the latch are written again to the counter, allowing the initial count value to be changed before starting the counter. you restart the down counter by setting the st_sp bit. the constant value can be either the initial value or a new one as shown on the following diagram: figure 32 . timer in single mode 4.3.1.6 output pin another pin, wdout (alternate function of p5.1 for ST92f150), when enabled by the outen bit, can change its state in two ways on the end of count of the main counter. basically, each time the counter overflows, it updates the output value. this can produce two different effects, selected by the outmd bit: either the state of the wrout bit is copied to the output at that time, or the output is complemented. st_sp counter value initial value end of count a new value may be written in the counter latches at any time. it will be transferred into the counter on end of count or on various conditions on wdtin and st_sp.
72/146 ST9 user guide figure 33 . output pin block diagram 4.3.2 timer application for periodic interrupts in this application, the clock is internal and the input and output pins are unused. the counter is set to continuous mode, and the value of the reload registers chosen so that the overflow occurs exactly every 128 microseconds. 4.3.2.1 initialisation of the wdt for a periodic interrupt very few registers are involved when you use the wdt for this purpose, since there is no input apart from the internal clock and no output. however, the wdt interrupt handling is a little dif- ferent from most other peripherals in that it borrows the interrupt circuit named inta0 that is normally assigned to external interrupt pin int0. so you configure the wdt in two steps: ini- tializing the wdt itself, and also the external interrupt inta0. in this example application, the internal frequency is 24 mhz and the interrupt rate must be 8192 hz. the timer starts with the preset count on the low-to-high transition of the st_sp bit of the wdt control register. the initialisation routine for the wdt is then: d 0 7 1 0 wdtcr (r251 page 0) timer/watchdog control register logical level user definable while counter is running wdtout pin eoc st_sp s_c inmd1 inmd2 outmd wrout inen outen
73/146 ST9 user guide /* *********** configure watchdog for periodic interrupt *************/ void configwdt ( void ) { selectpage( wdt_pg ) ;/* select watchdog page */ wdtpr = 0 ;/* 122 us = 366 ticks */ wdtr = 365 ;/* preset is nb ticks-1 (wdtr is the pair wdtlr and wdthr) */ wdtcr = (wdtm_stsp) ;/* wdt is set to continuous mode, no inputs, no outputs */ /* interrupt must be connected to inta0 in the eivr register */ } the initialisation routine for inta0 follows. in this example application, interrupt a0 is the only "external" interrupt enabled, and it is assigned priority level 2: /* ***********initialise interrupt a0 and current level **************/ void configinterrupts ( void ) { selectpage( exint_pg ) ; eivr = (eim_tlism+(unsigned char)inta0vect) ;/* int. a0 is generated on wdt overflow */ eiplr = 1 ;/* intr a0 (and that of same group) with high priority */ eimr = eim_ia0m ;/* intr a0 alone enabled */ cicr = (im_gcenm+im_iamm+im_ienm)+7 ; /* current processing level: minimum ; int. enabled, nested mode */ /* this starts also the mft */ } 4.3.3 watchdog application 1: generating a pwm this application provides a pwm with a programmable duty cycle. you can use it as an appli- cation exercise for learning to use the programming and debugging tools since it is very simple. the only hardware required to watch the effect of the program is a led in series with a resistor connected between p4.4 and vcc (anode towards vcc). you will find the application in the companion software in the wdt/appli1 directory. the wdt can only provide a delay after which the output may change its state, and an inter- rupt is triggered. the principle of using the wdt as a rectangular signal generator is to set it to continuous mode, to load it with a time value, and let it count down until zero. the control register is set so that an interrupt is then generated, and the output pin is updated at the same time. the interrupt service routine will reload with the other value, and preset the wrout bit to the complement of the current value, so that the opposite state will be transferred to the
74/146 ST9 user guide output pin at the next end of count. by alternating between two time values, a duty cycle other than 50% can be obtained (pwm). when the interrupt occurs, the output has already changed its state, so that the waveform can be very precise since it depends only on the timer hardware and not on the software. all that the interrupt service routine has to do is to load the timer latch with the value to be used when the end of count is reached. thus, the constraint is that the re- load interrupt must be guaranteed a latency time less that the shortest time between two output transitions. this may or may not be difficult to realize according to the intended timing and the presence of portions of the program where the interrupts are disabled. it is thus rec- ommended to properly manage the interrupts and thoroughly use the priorities to achieve this requirement. the wdt does not have an interrupt cause and a vector of its own. it must borrow them either from the top level interrupt or the inta0 input. we have chosen to use inta0 here, and to give it a priority of 6 which is high, but not the highest (which is 0). 4.3.4 watchdog application 2: using the watchdog a watchdog timer is a safety measure to prevent a program going adrift. it relies on a hardware timer that must be periodically reset by the program. failing to do this will reset the whole pro- gram (at the end of count). you will find it in the companion software in the wdt/appli2 di- rectory. the efficiency of this approach varies with the type of program and depends on the following conditions: the hardware action to perform in order to reset the timer must be so complex that if the pro- cessor goes adrift, it cannot accidentally reset the watchdog. in the ST9, you need to write 0aah and 055h successively to the wdtlr. the chosen time-out value must be greater than the interval at which the program resets the watchdog. it must also be as close as possible to that interval for maximum safety. since the watchdog time-out value is set once at the beginning of the program, this condition is best ful- filled if the resetting action is performed at constant intervals. a special software arrangement must be designed to reduce the chance that the part of the program that resets the watchdog can continue undisturbed when other parts of the program are faulty. this may include an interlock mechanism that requires that several program branches be executed to enable the resetting of the watchdog count. as you can see, achieving a very secure program malfunction detection by the sole means of a watchdog is a very difficult thing to realize. however, the watchdog can still play a key role in the safety of some systems, an example of which is an induction motor controller.
75/146 ST9 user guide 4.4 multifunction timer this device is the most powerful of the ST9 on-chip peripherals. this description only covers its main features. you can study the more intricate details with the help of an ST9 datasheet. the multifunction timer can handle many different operating modes; so many in fact, that vir- tually the only limit is your imagination. let ? s first have a look at the general organization. the first diagram in figure 34 represents the inputs and outputs, the prescaler register and the clock selection blocks, with their associated configuration registers.
76/146 ST9 user guide figure 34 . mft input/output modes the two outputs are actually the q outputs of a flip-flop which set and reset. flip-flop inputs can be individually configured to receive pulses from either of the following events: compare with cm0, compare with cm1, and overflow/underflow. this is used to generate single-shot or periodic wave forms simply by using the timer. input pin configuration input pin function clk logic u/d logic clear logic 8 bit prescaler 16 bit counter of the mft action on outputs after a successful event on output pin configuration internal clk/3 txina pin txinb pin txouta pin txoutb pin 3 bits of tcr 2 bits of tcr 4 bits of icr 4 bits of icr clock u/d clear 5 bits of flagr 8 bits of oacr 8 bits of obcr 2 bits of tmr (output enable)
77/146 ST9 user guide in addition to providing output signals, the timers can generate so-called ? internal events ? that can be used to synchronize other internal peripherals such as the dma and the analog to dig- ital converter. not all peripherals to be synchronized can be connected to just any mft. for each ST9 variant, the connection between each mft and the other peripheral is unique. refer to the corresponding datasheet for more information. the second block diagram represents the counter, the capture and compare registers, the re- load logic and the associated configuration and status registers. the interrupt and dma blocks are not represented. figure 35 . mft simplified block diagram in the above diagrams, the interrupt and dma logic are not represented. they obey the gen- eral interrupt and dma rules described earlier, and are controlled by three registers. the interrupt vector register controls the location of the interrupt vectors in program memory. they must be located at addresses that are multiples of 8. vr02111j 2 bits of flagr (result:) (result:) 6 bits of tmr 1 bit of tcr 1 bit of cicr compare 1 register compare 0 register compare logic 16-bit counter with comparator capture/load register 0 capture/load register 1 load/capture/monitor logic counter enable 1 bit of tcr (ovf/unf) (result:) 2 bits of flagr clock u/d clear
78/146 ST9 user guide figure 36 . mft interrupt vector register the interrupt and dma mask register individually enable and disable the various interrupt and dma sources. figure 37 . mft interrupt and dma mask register the upper five bits of the interrupt and dma control register indicate the status of the inter- rupts and the dma blocks. the lower three bits set the interrupt and dma priority level. 0 7 0 0 0 1 1 0 1 1 ivr (r242 page 9 mft0) (r246 page 9 mft1) interrupt vector register not used msb of the vector by software inside the interrupt vector table address table, fixed lsb of the vector address table, fixed by hardware overflow/underflow event interrupts not available capture event interrupts compare event interrupts interrupt source v4 v3 v2 v1 v0 w1 w0 d0 0 7 idmr (r255) interrupt / dma mask register ovf interrupt mask compare 1 interrupt mask compare 0 interrupt mask compare 0 dma mask capture 1 interrupt mask capture 0 interrupt mask capture 0 dma mask global timer interrupt enable gtien cp0d cp0i cp1i cm0d cm0i cm1i 0ui
79/146 ST9 user guide figure 38 . mft interrupt and dma control register the input and output control register has only two active bits. they are used to internally connect the output a of each mft to its own input a. one bit does this connection for all even- numbered mfts, and the other for all odd-numbered mfts. figure 39 . mft i/o control register 4.4.1 generating two pulse width modulated waves with one mft 4.4.1.1 description example the multifunction timer is used here as a double pulse-width modulator. it is also possible to have a single pwm output if needed. let ? s look at a simplified block diagram of the mft showing only the functional blocks that are actually used. see figure 40 . this is possible using the two comparators that simultaneously compare each capture register with the free-running counter. when the counter overflows, it is reloaded with the contents of the load register 0. at that time, both outputs are reset. when the value of the counter becomes equal to one of the compare registers, a pulse is sent to the output flip-flop of the corresponding side, thus setting the output. so the low time is the time between the counter overflow and the comparison. the high time is the remainder of the period. 0 7 idcr (r243, page 9, mft 0) (r247, page 9, mft 1) interrupt/dma control register interrupt/dma priority level cpe cme dcts dctd swen pl2 pl1 pl0 0 7 s c 1 s c 0 iocr (r248) i/o connection register iocr (r248) txina and txouta internally connected or not for each even mft. txina and txouta internally connected or not for each odd mft.
80/146 ST9 user guide figure 40 . mft block diagram figure 41 . using a counter and 2 compare registers to modulate 2 pulse widths actually, as nearly everything is configurable by values in control registers, this is only one of the ways to do it. in particular, the direction of the counter (upward or downward) and the ef- fect of the actions on the outputs (set/reset) can be chosen at will. compare register 1 comparator 1 free-running comparator 0 counter compare register 0 load register 0 prescaler set reset reset set cpu clock clock full count phase a pwm phase b pwm compare signal overflow signal compare signal output b output a reload value register 0 value compare register 1 value compare current contents of the counter
81/146 ST9 user guide this value of the load register determines the frequency of the output signals. for example, with a reload value of 255 and a 25 mhz internal clock, the pwm frequency is 1/256 of the 25 mhz clock divided by 3, that is 32,552 khz. in this case, the range of the compare registers is 1 to 255 inclusive. a value of 0 locks the outputs to the high state. to use the timer to deliver variable pwm, we need to change the value of the compare regis- ters from time to time. the simple way that first comes to mind is to write into the compare reg- ister whenever we need to update the pwm rate. this can lead to problems. if we write the new value into the compare register while the counter value matches the pre- vious contents, this can make the comparison fail and the pulse that changes the state of the output is not produced. the result is the output signal misses one cycle, as follows: figure 42 . compare register is modified while its content matches counter this will obviously have a bad effect on the electronic circuit connected to this output. another problem can occur if the reload value exceeds 255. then, two bytes are needed to ex- press the compare values. since the ST9 is an 8-bit machine, the two bytes that make up the word are sent one after the other. if the high bytes of the old and new values are the same, there is no problem. but if they differ, there are three possibilities for the value in the compare register: ? the register contains the old value ? the register contains one byte of the old value, and the other byte of the new value ? the register contains the new value reload value compare register 0 value output a this pulse is missing. this comparison has failed
82/146 ST9 user guide depending on the relative values of the old and new values, on the order of writing the bytes (high byte first, or low byte first), and on the direction of the timer (up-counting or down- counting), various things may happen. these can range from a missed comparison (see figure 42 ) to two comparisons in the same cycle (not a problem). this indicates that you have to pay attention to the time at which the compare register has to be updated. if we consider that the duty cycle does not vary widely from one cycle to another, the safest time to change value is as soon as possible after the match. the best way to do it is to store the new value in a variable (a register is a good choice), and configure the mft to trigger an interrupt when the match occurs. then, the interrupt service routine is executed and the new value is safely copied into the compare register. 4.4.2 generating a pulse width modulated wave with a cleaner spectrum the use of a mft to produce two pwm signals is convenient, especially for example in a stepper motor application. there, an ST92f150 is used and only one mft is available for pwm generation, since the other one is used for other purposes. however, this method suf- fers from a parasitic phase modulation of the signal since the falling edge is fixed, and the rising edge moves with the desired duty cycle. this leads to the production of unwanted har- monics in the resulting spectrum. this is not a problem for a lot of applications. sometime these harmonics are prohibited. example: when we want to drive a high power in- duction motor, these harmonics have two serious drawbacks: ? they produce parasitic frequencies that are injected in the mains, which is not allowed by power distribution companies, ? they feed the induction motor with even ranked harmonics, which degrade the efficiency of the motor and reduce the peak output power. you can improve this situation by using a symmetrical pwm generation, producing waveforms as follows: figure 43 . symmetrical pwm waveforms you use the mft in the following way. one mft being used for one output signal, you use only output a. you configure it so that it is set on a comparison with compare register 1, and reset on a comparison with compare register 0. these registers are always loaded with values 82% 18% 50%
83/146 ST9 user guide that are symmetrically centred on half of the reload value. for example, if the reload value is 255, the compare registers are set to the following values: you need to ensure that the compare registers are not written while they are used for a com- parison. because of this, they are written in an interrupt service routine that is triggered by the mft itself. to allow maximum latency time, the interrupt is triggered either by a compare 0 or a compare 1 event, according to the value of the duty cycle. for duty cycles between 0 and 50%, the compare 0 event is used. between 50% and 100%, the compare 1 event is used. the following figures shows the timing diagram. figure 44 . output a timing duty cycle compare register 0 compare register 1 10% 115 140 25% 96 159 50% 64 191 75% 32 223 90% 13 242 output a reload value compare register 1 value compare register 0 value reload interrupt
84/146 ST9 user guide 4.4.3 incremental encoder counter an incremental encoder is a device that generates two square signals in quadrature when its shaft rotates. its main specification is the number of cycles per revolution, i.e. the number of square signal cycles for one shaft revolution. the greater the number of cycles, the more ac- curate it is, and the more it costs. in a stepper motor application, it is used to monitor the rotation of the motor. here however, we have taken an encoder that has a great resolution, and this section will show you how to use an mft to count encoder pulses, and rescale it to another resolution to meet your project needs. 4.4.3.1 description the mft includes an input block, a counter block, an event block and an output block. in this application, no output signal is required, since the counter is expected to produce a value that is read in registers. the mft must provide the following functions: ? use the inputs to drive the counter according to the amount and direction of rotation ? keep the count undisturbed by events other than the transitions at the inputs ? allow reading the current counter value ? allow setting the counter to an arbitrary initial value we configure the input block to use the two square signals delivered by the encoder to drive the up and down counting of the counter. we do this using a special mode of the input block called ? autodiscrimination ? . in this mode, the input pulses clock the counter, and the phase re- lationship between the two signals selects up or down counting. since the process is incre- mental, once the mft configured this way, it automatically follows the rotation of the encoder shaft and the counter value reflects its position relative to the position it was in when the counter was configured. in our example, the encoder produces 512 cycles per revolution. be- cause the counter is 16-bit, it can monitor shaft positions 65536/512 = 128 (or +/-64) full rev- olutions from the original position. to operate with an encoder as the input pulse source, we need to set the mft to continuous mode. when the counter crosses the ffff to 0000 boundary in either direction, this is called an end-of-count event. in the normal continuous mode, the end-of-count event reloads the counter with the contents of reg0r (or reg1r in biload mode). in this application, no auto- matic reload may occur at any time so we can use the full range of the counter and be able to cross the boundary. to prevent the reload from occurring, we must set the reg0r register to capture mode. the mft is then said to be in free-running mode. we have thus selected free-running mode, yet we need to be able to set the counter to any arbitrary value that is taken as the initial position. for this we need to use the reg0r register
85/146 ST9 user guide as the load register. the solution is to initialise the mft with reg0r in capture mode by set- ting the rm0 bit of the tcr register to ensure free-running mode. when we need to load a value in the counter, we temporarily clear the rm0 bit. then we set reg0r to the value that must be written in the counter. the cp0 bit in the flagr register is pulsed high to write the contents of reg0r into the counter. then we set bit rm0 again. 4.4.3.2 initialisation the code for initializing the mft is given below. note: the icr register sets the input to autodiscrimination mode. in this mode, the lower four bits are irrelevant. void configtimer1 ( void ) { selectpage (t1d_pg) ; t_reg0r = 0 ;/* this register is used to preload the counter */ t_reg1r = 0 ;/* this register is used to read the counter */ /* t_cmp0r and t_cmp1r are not used */ t_tcr = tm_cen ;/* enable counter */ /* the counter will not start until the global counter enable is set in register cicr */ t_tmr = tm_rm0 ;/* capture using reg0r and monitor using reg1r */ /* this mode is not desired, but is implies free-running, which we need */ t_icr = tm_ab_aa ;/* inputs used in autodiscriminating mode */ /* for so, the port 3 must be set to input on pins p3.4 and p3.6 */ t_prsr = 0 ;/* prescaler rate = 1 */ t_oacr = 0 ;/* output a not used */ t_obcr = 0 ;/* output b not used */ t_flagr = 0 ;/* not used */ t_idmr = 0 ;/* not used */ } 4.4.3.3 reading to read the value of the counter, you need to capture it in one of the registers, since the counter itself does not have an address and cannot be read directly. there are two ways of reading the counter: set one of the registers reg0r or reg1r to capture mode. a pulse on bit cp0 or cp1, re- spectively, transfers the contents of the counter to the corresponding register.
86/146 ST9 user guide put reg1r in monitor mode. in this mode, reg1r continuously reflects the value of the counter, without the need for pulsing a bit in a register. in the stepper motor application, we have chosen to use monitor mode. no special function is needed to read the counter. a simple assignment of reg1r to a variable is enough, such as: pos = reg1r ;/* get current counter value */ 4.4.3.4 updating as mentioned in section 4.5.3.1, updating requires switching the mode of reg0r from cap- ture to load. /* this function forces the mft1 counter to a value given in argument */ void setencoder ( int value ) { selectpage (t1d_pg) ; t_tmr &= ~tm_rm0 ;/* switch temporarily to "load with reg0r" mode */ t_reg0r = value ;/* set encoder */ /* convert motor position to match the encoder's resolution */ t_flagr |= tm_cp0 ;/* load counter with this value by pulsing cp0 high */ t_flagr &= ~tm_cp0 ;/* return cp0 to low */ t_tmr |= tm_rm0 ;/* go back to "capture with reg0r" mode that implies free-running */ } 4.4.4 mft application 1: generating 2 pwms using interrupts this application generates 2 independent pwm signals on pins t0outa and t0outb pro- vided that a logical low level is applied to gate t0ina. the outputs are reset on compare events and set on the counter underflow. this application is found in the mft/appli1 directory. counter compare interrupts are used to reload compare registers in order to modify the duty cycle. when running one of these three examples on an ST92f150 microcontroller, note that mft outputs are pure open drain. 4.4.5 mft application 2: generating a pwm using dma this application generates a pwm signal on pin t0outa using a dma channel to transfer duty cycle data from memory to register comp0. the dma transfer only occurs once as it is not re-initialized in the dma end of block interrupt routine. this application is found in the mft/ appli2.
87/146 ST9 user guide 4.4.6 mft application 3: generating a pwm using the dma swap mode this application generates a pwm signal on pin t0outa using the dma swap mode to transfer duty cycle data from memory to register comp0. this application is found in the mft/ appli3 directory. swap mode uses two sets of dma registers and swaps from one to the other at the end of each transfer. the end of block interrupt routine reloads the unused set of dma registers for the next transfer.
88/146 ST9 user guide 4.5 serial peripheral interface 4.5.1 description the spi is a synchronous input-output port that you can configure in various modes, including s-bus. it can have many more uses, of which two are considered here: interfacing with serial- access eeproms and interfacing with a liquid-crystal display. the main block of the spi is an 8-bit shift register which can be read or written in parallel through the internal data bus of the ST9, and that can shift the data in or out on two separate pins, named sdi and sdo, respectively. the serial transfer is initiated with a write to the spi data register (spidr). data is input and output simultaneously with each most significant bit being output on sdo while the level at sdi becomes the least significant bit. each time a bit is transferred, a pulse is output at the sck pin. when eight bits are transferred, eight pulses have been sent on sck, and the process stops. if the proper bits are set in the spi control register (spicr), an interrupt can be requested on end of transmission. to summaries: ? transfers are started by writing a byte into the spi data register ? data is input and output at the same time ? data is input and output with the most-significant bit being sent first ? eight clock pulses are output on the sck pin synchronously with bit shifting ? an interrupt request can be issued on end of transmission the spi is configured with the spicr register. four bits of this register are of special interest in the applications detailed here: these are the cpol-cpha pair, and the spr1-spr0 pair. the cpol-cpha pair defines the polarity and phase of the clock pulses. this allows them to adapt to the external device. cpol selects between rising edge or falling edge as the active transition, and cpha selects whether the first active edge is the first edge of the pulse train or the second one. the spr1-spr0 pair selects one of four different transfer speeds. 4.5.2 static liquid-crystal display interface example this example uses a static liquid-crystal display that shows a simple number. this can be the voltage in a digital voltmeter, or any 3 1/2 digit value. a very simple demonstration program is supplied in the companion software. some of the routines are reused in the bar code reader described later. a static liquid-crystal display is composed of a glass back-panel, and a set of front-panel elec- trodes printed on a glass front-panel. the space between both panels is filled with a liquid- crystal solution. the electrodes are transparent, and the panels may be fitted with a combina- tion of polarisers, so that the whole display, unpowered, is either transparent or opaque ac- cording to the selected polariser combination. when a difference of potential is applied be-
89/146 ST9 user guide tween one electrode and the backplane, the area delimited on the front panel by the shape of the electrode takes the reverse state, i.e. opaque or transparent, respectively. using a seven- segment pattern, it is possible to display numbers, by activating the appropriate segments to show the desired figures. a liquid-crystal display presents a high impedance between its electrodes, ranging typically in the megaohm region. it is thus a voltage-controlled device, with a threshold of about 3 v to change from one state to the other. driving such a display is then a simple matter, but one fun- damental precaution must be taken to avoid premature destruction of the display: it must be driven with alternating voltage, to avoid electrolysis within the inter-electrode solution. the fre- quency is of little importance, and the best values range between 30 and 100 hz. this basic explanation does not cover all the details and precautions relative to lcds but is sufficient to understand the use of the spi as a lcd driver. in this application, the display is installed on a separate board. since it has 40 pins, it is not convenient to connect this board with a 40-wire cable. using a serial synchronous transmis- sion, only four wires are required. the block diagram of the circuit of the display board is: figure 45 . lcd interface example as shown by this diagram, to make it easy to wire our display board, the correspondence be- tween the segment positions and the bit positions in the bytes transferred is actually: and the conversion between the figures (0 to 9) and the display pattern is done by a constant array defined in this case as: ; table of characters. gives the patterns for the last 3 digits, from 0 to 9. bit position 76543210 segment dp g f a b c d e liquid crystal display one digit 32 bit serial input, parallel output shift register ground serial input shift clock +5v a b c d e f g dp +1 back panel dp g f e d c b a dp g f e d c b a dp g f e d c b a
90/146 ST9 user guide characters: .byte 3fh, 0ch, 5bh, 5eh, 64h, 76h, 77h, 1ch, 7fh, 7eh the lcd electrodes are connected to the outputs of a serial input, parallel output shift register. the backplane is also connected to one output. this allows us to provide the a.c. drive for the electrodes, as shown in the table below: in short, the segment is on if its level is different from that of the backplane. it is off if its level is the same as that of the backplane. thus, to generate the drive pattern, it is only necessary to build the four bytes that correspond to the various segments, keeping the bit corresponding to the backplane at level zero. then, using a periodic interrupt, these four words are trans- mitted serially, but complemented every other time. as an example, to display the value 375, as in the demonstration program, the following message is built: since in this original message the backplane bit is kept at zero, all bits that are 1 correspond to an activated segment; the others remain invisible. this message is sent at intervals of about 16 ms, but it is inverted every other time, giving the succession: this succession of inverted words guarantee a zero d.c. component across the liquid crystal solution, which is absolutely necessary. level of the back- plane level of one of the segments state of the liquid crystal between the electrodes 00 off 0 1 on, positive voltage 1 0 on, negative voltage 11 off symbols hundreds tens units 00000000 01011110 00011100 01110110 symbols hundreds tens units 00000000 01011110 00011100 01110110 11111111 10100001 11100011 10001001 00000000 01011110 00011100 01110110 11111111 10100001 11100011 10001001 00000000 01011110 00011100 01110110 11111111 10100001 11100011 10001001 etc.
91/146 ST9 user guide 4.5.3 eeprom serial interface example using i 2 c an i 2 c serial eeprom is a very convenient device that stores a few bytes for at least 10 years in a secure manner. the serial i 2 c access uses only two wires, which allows the memory to fit in an 8-pin dil package. the serial access requires a serial transmission protocol, which makes the access more difficult than with a parallel-bus eeprom device. this, however, is not a real drawback, for two reasons: ? the serial synchronous transmission is very easy to implement, and is not time-critical ? using a serial protocol makes it impossible (or very unlikely) that you will overwrite or erase data by mistake, which ensures a high safety level for the application thus, for applications that can manage with a small amount of permanent data, a serial ee- prom is the best choice. examples include storing the reading of a counter or a recording meter, storing configuration parameters or calibration values. the application described here uses a 24c08 memory chip from stmicroelectronics, that takes advantage of the spi to ex- change data with minimum software overhead. 4.5.3.1 additional clock timing compared to i 2 c timing, spi timing needs additional software to manage the following: ? the start condition ? the ninth bit for acknowledgement ? the stop condition these three timing differences are implemented by changing the input/output port data and configuration registers, to pull the level on the sda and scl pins up or down. 4.5.3.2 eeprom i 2 c protocol to connect more than one device to an i 2 c interface, each device needs an address to be se- lected. the eeprom 24c08, used for our example, has an address equal to a0h. following a start condition, the bus master (spi) must output the address of the eeprom it is accessing. the most significant four bits are the device type identifier (1010). the following bit identifies the specific memory location on the bus (it is matched to the chip enable signal). once the 6th and 7th bits are sent, select the block number and the 8th bit sent is the read or write bit (1 for read, 0 for write). after the address has been sent, ten data bytes can be sent to the eeprom for writing, and all the data bytes can be read successively from the eeprom for verification.
92/146 ST9 user guide 4.6 serial communications interface 4.6.1 description the sci is the association of a uart and a complex logic that handles tasks such as char- acter recognition and dma. it can also work as a simple serial expansion port that then resem- bles the spi. the example given here appears as a classical uart application, viewed exter- nally, but it is assisted by the built-in dma controller to provide effortless transfers of data in and out of the application. as serial communication is a feature that is very often used, it will be found in all three applications. the sci has four operating modes: ? asynchronous mode where data and clock can be asynchronous. each data is sampled 16 times per clock period. the baud rate should be set to the 16 division mode and the frequen- cy of the input clock is set to suit. ? asynchronous mode with synchronous clock where data and clock are synchronous but the transmit and receive clock are asynchronous. the receive clock must be given by the exter- nal peripheral. ? serial expansion mode where data and clock are synchronous and the clock is supplied by the transmitter (ST9 in transmission and externally in reception). ? synchronous mode where data and clock are synchronous, the transmit data clock is sup- plied by the ST9 and the receive data clock is received by the external peripheral. in this mode there are no start and stop bits. these four operating modes allow you to connect the ST9 to any external interface. 4.6.1.1 uart the uart offers all the usual functions for asynchronous transfer. you can set it to handle word lengths of 5 to 8 bits, with or without parity, even or odd. it offers also the possibility to ap- pend a signalling bit (called address bit or 9th bit -- regardless of the word length) at the end of the transmitted data, just before the stop bit. this can be used to help design a multidrop network. the uart can be set to interrupt the processor only when this bit is high, indicating that the current character is an address or other identifier. this prevents the processor from being disturbed by the traffic on the network unless an address byte is received, so that the processor can check if it is concerned or not by the incoming data. the uart is set to 8 bits, 1 stop bit and no parity, by writing the appropriate value in the chcr register. a timer is part of the sci block. it is used as a baud rate generator (brg). it allows you to di- vide either the internal clock or the frequency available at the rxclk input pin, by an arbitrary value. this output can be fed to the receive and transmit sections, though each section can
93/146 ST9 user guide have its own clock frequency supplied on pins rxclk and txclk for receive and transmit, respectively. here, we use the brg to clock both sections. at the clock input of the transmit and receive shift registers, two other dividers can be inserted, to further divide the frequency by 16. it must be used in asynchronous mode to allow detection of the start bit using a local clock. if an external clock is supplied, at the same frequency and phase as the serial incoming data, the 16x divisor must not be used. here, the predivisor is used. the uart is surrounded by logic that allows it to detect errors on reception, a break state on the line, and also to recognize a match between the character received and a reference char- acter stored in a register. this last feature is used here. the acr register is loaded with the value 10 representing the lf character, and the imr interrupt mask register is set to enable an interrupt on a character match. since dma is used to transfer the incoming characters to memory, this technique is used to detect the end of message, if we state that all commands must end with an lf character. 4.6.1.2 dma controller the dma is used for the automatic data transfer from memory or a register to the serial trans- mitter or from the serial receiver to a register or memory, or both. the working of the dma in conjunction with the uart merits some detailed explanation, be- cause it is subtle and you need to take some precautions to make it work properly. once ini- tialized, it is easy to use and it consumes very little computing power to initialise transmission or re-enable reception. the dma transfers in each direction are controlled by two registers: the dma transaction counter and the dma pointer. the transaction counter is used to stop the transaction when a predefined number of characters is transferred. the dma pointer points to the character to be sent or to the location that will hold the next character to be received. to initialise a dma transfer, the transaction counter must be set to the number of characters to be transferred and the dma pointer must be set to the beginning of the storage area that contains the data to be transmitted or that will hold the data string received. transfers can occur between the uart and either the memory or register file. the transaction counter and the dma pointer must be registers in the register file. if the reg- ister file is involved in the transfer, both the transaction counter and the pointer must be single bytes (the addressing range of the register file is 0 to 255). if the memory is involved, the counter and the pointer must be each a pair of registers, since the addressing range in memory is 0 to 65535 for one segment. once you have defined in which registers you will put the counter and the pointer, you must let the sci know. the sci has two registers for this purpose called the dma address pointer
94/146 ST9 user guide register (dapr) and dma counter pointer register (dcpr). these registers are not the ac- tual counter and the pointer, they point to where you want to locate them in the register file. this double pointer mechanism is similar to that described for interrupts. here there can be two cases: the transfer involves the memory or the register file. if the transfer involves the memory, it ? s standard procedure. the dcpr points to the 16-bit counter register, and the dapr points to the 16-bit address register. these two register pairs may reside anywhere there is room for them in the register file. since register pairs are used, their addresses are even. the dcpr must be even. to reach the dma segment the dmasr (or isr depending on dapr bit 0) mmu register contains the segment number. if the transfer involves the register file, things are a bit different. both the transaction counter and the address register are 8-bit values. they are supposed to be adjacent in the register file, i.e. they occupy two successive registers: the first one, even numbered, is the address reg- ister. the second one, odd numbered, is the transaction counter. to select this mode, the least significant bit of the dcpr must be one. its value is the address of the address register (which is even) plus one. the dapr is not used. the whole mechanism described above applies for both the transmitter side and the receiver side. thus, there are twice as many registers as mentioned: the tdcpr and the tdapr for the transmitter side, the rdcpr and the rdapr for the receiver side. the registers you have located in the register file are also twice as many. so, the tdcpr points to the transmitter transaction counter and the tdapr points to the transmitter address register (with the excep- tion mentioned above if the transaction involves the register file). the rdcpr points to the re- ceiver transaction counter and the rdapr points to the receiver address register. when a dma transfer is in progress, the processor is not even aware of it (except that it is slightly slowed down by the stolen clock cycles). so nothing special has to be done as far as the program is concerned. the question is: how to start and end a dma transfer? here, the processor is involved, and some code is needed. depending on which side is concerned, the processes are different. 4.6.1.2.1 transmitter side to start a dma transmission, you need to do the following operations, in order: ? set the dma segment register dmasr (or isr) to point to the selected segment of data memory. ? set the transmit address register to the address of the second word to be sent (not the tdapr, which is only set once at initialisation, and points permanently to the transmit ad- dress register).
95/146 ST9 user guide ? set the transmit transaction counter to the number of characters to be transmitted minus one (not the tdcpr, which is also only set once at initialisation, and points permanently to the transmit transaction counter). ? set the txd bit of the idpr register. this bit enables the transmitter holding register empty flag (txhem bit of register isr) to trigger a dma transfer when the last character is sent. when txd is reset, the holding register empty flag would trigger an interrupt instead. ? load the transmit buffer register (txbr) with the first character to be sent. this starts the dma process as soon as this character is transmitted. ? clear the transmitter holding register empty flag (txhem bit of register isr) and the trans- mitter buffer register empty flag (txsem bit of register isr) to prevent dma transfer from starting before the first character is fully transmitted. ? enable the end of dma interrupt by setting the transmitter data interrupt mask (txdi bit of register imr). the dma is now started and will stop when the transaction counter reaches zero. note: the transmit address register is initialized with the address of the second word and the transmit transaction counter is initialized to the number of characters to be transmitted minus one, be- cause the dma transfer begins when the first word is transmitted (a write in the transmit holding register), so the first word is transmitted ? by hand ? . 4.6.1.2.2 receiver side the receiver side is a little more complicated as two kinds of events can occur during recep- tion: ? there can be transmission errors that must be handled. ? a break is received or a character match event can occur. the receiver is set in a ready for dma condition by the initialisation code. reception normally finishes when the dma transaction counter has reached zero. but this is not necessarily the way one wants to use the serial input, since it implies that the number of characters to be received must be known before the transfer starts. in most cases, character- type messages have a variable length. in this application, the transaction counter is not expected to reach zero, since the size of the buffer assigned for reception exceeds the longest message defined in the specification. thus, if the transaction counter reaches zero this is in fact an overflow condition. in this case, the contents of the buffer are discarded and a new reception is initiated. in both cases, the steps to perform an end of block are: ? reset the receiver end of block (rxeob bit of register imr) to remove the interrupt request. ? use the received characters, if required.
96/146 ST9 user guide ? re-enable the end of block interrupts by setting the receive dma bit (rxd bit of register idpr). ? restore the dma capability by setting the receive address pointer (not the rdapr) to the address of the beginning of the receive buffer. ? set the receive transaction counter (not the rdcpr) to the number of characters to be re- ceived. this will re-enable the dma capability. in a typical application, command messages could have variable length and be terminated by an lf character. so, the character match event capability built in to the sci should be used. if the address/data compare register (acr) contains the value 10 (ascii code for lf), and the receive address mask (rxa bit of register imr) is set, whenever an lf character is re- ceived, an interrupt is generated. this interrupt is considered in the application as a good mes- sage received signal. it is processed the following way: ? in this application, no other characters are expected until the previous message has been answered by the program. however, it may be useful to inhibit further dma cycles by clearing the rxd bit in the idpr register and also the rxdi bit in the imr register. ? read the receive buffer register (rxbr) to remove the interrupt request (see note below). ? make use of the received characters. ? restore the dma capability by setting the receive address pointer (not the rdapr) to the address of the beginning of the receive buffer. ? set the receive transaction counter (not the rdcpr) to the number of characters to be re- ceived. this will re-enable the dma capability. note: when matching occurs between the incoming character and the acr register contents, the dma request is not generated, neither is an interrupt request for ? character received ? . so, the incoming character remains in the receive buffer and no other character can be received until it has been removed. this is why it is not sufficient to clear the rxap bit in the isr register to reinstate the dma transfer. you must clear the rxbr register by reading it during the character match interrupt service routine. finally, an error may occur during transmission. this can be a parity error (if parity checking is enabled), a framing error or an overrun error. if one of these errors occurs, take the following steps: ? clear the bits that indicate an error condition in the isr register. ? restore the dma capability by setting the receive address pointer (not the rdapr) to the address of the beginning of the receive buffer. ? set the receive transaction counter (not the rdcpr) to the number of characters to be re- ceived. this will re-enable the dma capability.
97/146 ST9 user guide 4.6.1.2.3 interrupt vectors the interrupt vector scheme has been explained in section 3.4.1 using the example of the mft to illustrate the mechanism. here is the equivalent table for the sci giving the position of the four vectors dedicated to the four interrupt causes. 4.6.2 sci application 1: sending bytes using interrupts this application sends 10 bytes to the usart. an interrupt is generated at the end of every single byte transmission. during this interrupt routine, the txbr register is loaded with the next byte to be transmitted. this application is found in the sci/appli directory. the character format is: 2400 bauds, 8 data bits, 1 stop bit and odd parity. sent bytes can be received on a pc loaded with a serial communication management software program such as hyperteminal. 4.6.3 sci application 2: sending bytes using dma this application sends bytes from the memory to the sci peripheral using a dma channel. the transfer is re-initialized twice in the dma end of block interrupt routine so that data is transmitted three times. this application is found in the sci/appli2 directory. 4.6.4 sci application 3: sending and receiving bytes using dma this application sends bytes from the memory to sci and receives bytes from sci to the reg- ister file using two dma channels. the sci cell is configured in loopback so that each byte sent is immediately received by the sci. this application is found in the sci/appli3 directory. 4.6.5 sci application 4: matching input bytes this application receives bytes from the usart and reacts only if an ? f ? (upper case) is re- ceived: on a character match, a ? 0 ? is displayed on the 7-segment led display on port 4. this application is found in the sci/appli4 directory. value in ivr 50 interrupt cause address in rom of the selected pointer value of the pointer to interrupt routine receiver error 50 address of error processing routine break detect or address match 50+2 address of address match process- ing routine receiver data ready or dma end of block 50+4 address of receive dma end of block processing routine transmitter buffer empty of dma end of block 50+6 address of transmit dma end of block processing routine
98/146 ST9 user guide 4.7 analog to digital converter 4.7.1 description the analog to digital converter is one of the simplest peripherals of the ST9 family to use. it converts the voltage applied to one of sixteen inputs using an 10-bit successive approximation analog to digital converter. according to the value of bits sc3, sc2, sc1 and sc0 of the con- trol logic register (clr1, r252, p63), one to sixteen inputs are converted at each conversion cycle, starting at the channel number specified by these bits and ending with channel 15. the simplified block diagram is the following:
99/146 ST9 user guide figure 46 . a/d converter block diagram the conversion cycle can either be started in single mode, by a trigger (software or hardware, the later being internal or external) or in continuous mode, restarted as soon as the previous cycle is finished. each channel uses one bit of a port (the port depends on the variant of the ST9), and the con- version result is stored in a 16-bit register. sixteen such registers are available, named ad_d0r to ad_d15r. these 16 bit registers are data registers are made up of two 8-bit reg- 16 10 2 a/d end of conversion or awd interrupt to the core 3 bits of cicr 4 bits of ad_icr priority mechanism 1 bit of ad_ivr a/d or awd interrupt vector selection pending & mask bits 4 bits of ad_crr compare result analog watchdog threshold registers 16-bit h/l( c h.a) threshold registers 16-bit h/l( c h.b) 4 bits of clr1 data register a/d converter ain pins channels 0 to 16 autoscan logic see fully detailed diagram of the a/d converter in section 6 synchronisation to start/stop the a/d converter 4 bits of clr1 extrg pin 3 bits of ad_icr 2 4 bits of
100/146 ST9 user guide isters e.g ad_d0r is made up of ad_d0lr (for lower 2 bits of 10 bits result) and ad_d0hr (for upper 8 bits of 10 bits result). the end of conversion sets the ecv bit in the ad_icr register, and can trigger an interrupt re- quest, if the eci bit (mask of the end of conversion interrupt request) of the interrupt control register (ad_icr) is set. notes the internal interrupt controller does not automatically reset the ecv bit. it must be reset by the interrupt service routine prior to returning from interrupt. failure to do this would cause the in- terrupt to loop endlessly. as mentioned in section 4.2 on parallel ports, you must configure the corresponding pins to alternate function both to reduce loading on the analog source and to avoid excessive dissipa- tion in the pin's input buffer. for the same reason, it is advised to keep this i/o configuration if an analog voltage is present on the pin, even if it is not being converted at this time. 4.7.2 analog watchdog a special feature of this peripheral is the so-called analog watchdog. if enabled, the values of channel a or both channel a and channel b are each compared after each conversion with a pair of upper and lower thresholds stored in registers ad_ltar (ad_ltahr,ad_ltalr), ad_utar(ad_utahr,ad_utalr) for channel a, and ad_ltbr(ad_ltbhr,ad_ltblr), ad_utbr(ad_utbhr,ad_utblr) for channel b. channel a and channel b are selected by cc[3:0] bits in control register ad_clr1. if the value is outside the threshold values, the awd bit of the ad_icr register is set. this can trigger an interrupt request if the awdi bit of the same register is set. to know which of the four thresholds has been exceeded, the compare result register (crr) has four bits with one each corresponding to one of these thresholds. the appropriate bit is set when the threshold has been exceeded. notes: the awd bit, like the ecv bit, is not automatically reset by the internal interrupt controller. thus it must be reset by the interrupt service routine prior to returning from interrupt. failure to do this would cause the interrupt to loop endlessly. to permit power saving in applications where energy conservation is important, you can power the adc on and off so that it only consumes power when used. however when you switch it on, after a delay of 10 s first conversion starts. the reset condition is off. 4.7.3 interrupt vectoring two vectors are dedicated to the adc: the end of conversion vector and the analog watchdog vector. this allows these two events to be serviced by two different routines. the vectors used depends on the state of the w1 bit in the ad_ivr register. this bit is set or reset according to the source of the interrupt. however, it may occur that both interrupts are generated simultaneously. in that case, analog watchdog has priority over end of conversion request.
101/146 ST9 user guide 4.7.4 adc application: a/d conversions and analog watchdog using interrupts this application converts the analog value presented on p7.7 and enters the conversion re- sults in a chart as long as the converted value resides within the user-defined threshold. the end of conversion interrupt is used to transfer the result of the conversion to the chart. the an- alog watchdog interrupt, when triggered, stops the a/d converter. this application is located in the adc/appli directory.
102/146 ST9 user guide 4.8 peripheral initialization all the ST9 peripherals have a large number of configuration options. this makes them highly adaptable, but has a complex initialization procedure. to help you to use the peripherals easily, you can find all the initialization programs on the internet site. the purpose of these programs is to give you c language programs to get started with pro- gramming each peripheral. this program package consists of a header file, a peripheral func- tion, a startup and a main program for each peripheral. the startup (crtbegin.spp) and the main (main.c) files are not explained here. have a look at these files for more details. all you now have to know is that whenever an interrupt subroutine is used, the startup program is initialized with the interrupt subroutine address. for example the intadc_endconv() adc interrupt subroutine address declared in the file is loaded in the startup routine at the interrupt vector register loca- tion. 4.8.1 initialization header file the initialization header file defines all the constants, the file to be included, the function pro- totypes and the peripheral mode. the initialization header file has to be included any time the peripheral is referenced. the next section uses the analog to digital converter peripheral file as an example. the adc initializa- tion header file is . 4.8.1.1 constants already initialized and to be initialized the file is complementary to the header file located in the toolchain header files directory, with the other peripheral header files. the 16 initialized constants, channel0 to channel15, give you the 16 possibilities of ini- tializing the non-initialized constant ad_channel. this constant will initialize the ad_clr1 adc control logic register1 in the file. 4.8.1.2 files to be included the files to be included contain other initialized constants like in the previous file.
103/146 ST9 user guide 4.8.1.3 function prototype declarations each of these functions can be called by the main program or other functions for managing the adc. they are defined in the file. the file function prototypes are: void init_adc(void); void start_adc(void); void stop_adc(void); void init_adc_it(void); void enable_adc_it(void); 4.8.1.4 defining the functional mode to initialize the peripheral mode, you can activate the define directive by removing the <>. e.g.: in the file, you can select continuous mode with: #define continuous /*#define single*/ 4.8.2 peripheral function file these files contain the peripheral management functions. the function prototypes are placed in the header file as explained before. the functional mode and the constants initialized in the header file modify the functions so that they can be used directly by the application program. presentation of peripheral function files:- 4.8.2.1 adc file the adc function file is and contains 6 functions initialized for using channel 15 of the adc corresponding to i/o port p7.7. it performs 15 conversions and stores the converted values in chart.. moreover, the analog watchdog is enabled on this channel and stops the se- ries of conversions if the value is not within the prescribed thresholds. table 4. adc.c functions function description and comments void init_adc(void); choice between continuous and single-shot modes. possibility of initializ- ing the analog watchdog on channel a or/and b. void start_adc(void); choice between three triggers to start the conversions: internal, external or software. v o i d s t o p _ a d c ( v o i d ) ; this routine stops the adc after a series of conversions. afterwards, all power consuming logic is disabled (low power idle mode).
104/146 ST9 user guide 4.8.2.2 mft file 4.8.2.2.1 mft files without dma the mft function file is and contains 6 functions that are initialized for gen- erating two pwm signals using the two output pins of the mft0. compare0 and compare1 events are managed by interrupts. input a is used as a gate: as long as a +5v level is applied on it, the counter stops down- counting and the pwm signals are thus not generated. the following ports are used for this: ? t0outb ? t0outa ? t0ina table 5. appli1\mft.c functions 4.8.2.2.2 mft files with dma the mft function file is and contains 7 functions that are initialized for gen- erating a pwm signal using the mft and a dma channel. void init_adc_it(void); the pointer to the array of two it vectors dedicated to the ad is initialized. the priority of these interrupts is initialized. this routine initializes both end of count and analog watchdog. don't forget to initialize your start-up file correctly. void enable_adc_it(void); this routine enables interrupts: end of conversion or/and analog watch- dog. void intadc_anawd(void); interrupt subroutine dedicated to analog watchdog. void intadc_endconv(void); interrupt subroutine which occurs after an end of conversion event. function description and comments void init_mft(void); mft initialization. it initializes the value loaded into the prescaler and into the counter. void start_mft(void); start the mft. void stop_mft (void); stop the mft. void init_mft_it(void); this function configures the it for the mft. void enable_mftcm_it(void); enables compare0 and compare1 it. void intmft_compare(void); interrupt subroutine which occurs after: - compare 0 - compare 1 only one it vector. function description and comments
105/146 ST9 user guide the port used for this application is: ? t0outa table 6. appli2\mft.c functions 4.8.2.2.3 mft files with dma in swap mode the mft function file is and contains 6 functions that are initialized for gen- erating a pwm signal using the mft and a dma channel working in swap mode. the port used for this application is: ? t0outa function description and comments void init_mft(void); mft initialization. it initializes the value loaded into the prescaler and into the counter. void start_mft(void); start the mft. void stop_mft (void); stop the mft. void init_mft_itdma(void); this function configures the it and the dma for the mft. void enable_mftcp0_dma (unsigned int * compbuffer, unsigned int count); enable compare0 dma. void intmft_compeob(void); interrupt subroutine which occurs after a compare0 dma end of block. the dma is not re-initialized so only one block is transferred. same vector as compare0 interrupt. void intmft_ouf(void); interrupt subroutine which occurs after an underflow. it stops the timer when the whole pwm signal has been generated.
106/146 ST9 user guide table 7. appli3\mft.c functions 4.8.2.3 rccu file the rccu file is and contains 5 functions for controlling the rccu in your ap- plication. the header file has no uninitialized constants since the functions are dedicated. table 8. rccu.c functions 4.8.2.4 sci file 4.8.2.4.1 simple sci files (sci-m) the sci function file is and contains 4 functions that are initialized for sending ten bytes from the ST9 to the serial link (rs232). it uses end of transmission interrupts. port used: ? tx (s0out) function description and comments void init_mft(void); mft initialization. it initializes the value loaded into the prescaler and into the counter. void start_mft(void); start the mft in the swap mode. void stop_mft (void); stop the mft. void init_mft_itdma(void); this function configures the it and the dma for the mft. void enable_mftcp0_dma(un- signed int * compbuffer, un- signed int count) enable compare0 dma. void intmft_compeob(void); i nterrupt subroutine which occurs after a compare0 dma end of block. the dma is swapped. function description and comments void init_pll(void); initialize the pll, mul. by 6, div. by 1. wait 500s to stabilize the pll. void init_clock2(void); intclk = clock2 = ext oscillator / 2. void init_clock2_16(void); intclk = clock2/16 = ext oscillator / 32. void switch_to_extclk(void ); stop the xtal oscillator and select the external clock (if present). void back_to_xtal(void); restart the xtal oscillator and select it as the clock source.
107/146 ST9 user guide table 9. sci.c functions 4.8.2.4.2 sci files using dma the sci function file is and contains 4 functions that are initialized for sending 26 bytes from the ST9 to the serial link (rs232) by using the dma. it uses dma channel (from memory). port used: ? tx (s0out) (uses end of transmission interrupts) function description and comments void init_sci(void); initialization of general parameters dedicated to the sci: - baud rate generator: 9600 bauds. - characters: eight data bits, one stop bit, odd parity. - pins... the baud rate generator must be initialized following this structure (brghr first and brglr at the end). void init_sci_it(void); initialization of the it: vector, priority. void sci_sendbyte(un- signed char tosend); it sends byte tosend to serial link. this routine also enables end of transmission it. void intsci_transmitready(voi d); interrupt subroutine which occurs after the transmission of one charac- ter. if 10 bytes have been transferred, it disables the it and so stops the trans- mission.
108/146 ST9 user guide table 10. sci.c functions 4.8.2.4.3 sci files using dma in the loopback mode the sci function file is and contains 5 functions that are initialized for sending 26 bytes from memory to the serial link. the sci is in loopback mode, so that the bytes sent are then received by the sci and stored in the register file (from r16). it uses dma channels: ? from memory to peripheral for the transmission ? from the peripheral to the register file to receive the bytes. no ports are used. 4.8.2.4.4 sci files using character matching the sci function file is and contains 5 functions that are initialized for re- ceiving data on the input pin of the sci and it only reacts when it receives character sci_match (defined in sci.h). port used: rx (s0in) function description and comments void init_sci_dma(void); initialization of general parameters dedicated to the sci: - baud rate generator: 9600 bauds. - characters: eight data bits, one stop bit, odd parity. - pins... the baud rate generator must be initialized following this structure (brghr first and brglr at the end). initialization of the it: vector, priority. initialization of dma in transmission void start_senddma(un- signed char * transmitbuff- ermem, unsigned int sci_count); after a few extra initialization, the transmission starts by loading data reg- ister(txbr) with the first value to send. void intsci_transmiteob(void) ; interrupt subroutine which occurs when a whole block of data has been transferred using dma. in fact, the buffer ? table ? is sent three times and then dma is disabled.
109/146 ST9 user guide table 11. sci.c functions 4.8.2.5 timer file standard timer function file is and contains 6 functions that are initialized for gen- erating a simple pwm signal using the standard timer (programmable duty cycle). port used: ? stdout table 12. timer.c functions function description and comments void init_sci(void); initialization of general parameters dedicated to the sci: - baud rate generator: 9600 bauds. - characters: eight data bits, one stop bit, odd parity. - pins... the baud rate generator must be initialized following this structure (brghr first and brglr at the end). void init_sci_it(void); initialization of the it: vector, priority. the only interrupt which is enabled is ? character match ? . void intsci_receivematch(void); this interrupt subroutine occurs when the sci cell has received the matching character. in this example, it displays 0 on a 7-segment led connected to port 4. function description and comments void init_st(void); standard timer initialization. it must be used before any use of the st. it initializes the value loaded into the prescaler and into the counter. to use the st in output mode, you must initialize the output pin in push- pull, alternate function . this means (pxc0r,pxc1r,pxc2r) = (1,1,0). void start_st(void); starts the standard timer. void stop_st (void); stops the timer counter. void init_st_it(void); this routine configures the interrupts after each end of count. don't forget to initialize your start-up file correctly. void enable_st_it(void); enables the standard timer interrupt. void intst_endcount(void); interrupt subroutine which occurs after an end of count.
110/146 ST9 user guide 4.8.2.6 wdt file 4.8.2.6.1 wdt files for pwm generation the wdt function file is and contains 7 functions that are initialized for generating a simple pwm signal using the wdt (programmable duty cycle). port used: ? wdout table 13. wdt.c functions 4.8.2.6.2 wdt files in watchdog mode the wdt function file is and contains 4 functions that are initialized for en- abling the wdt in watchdog mode and refreshes it regularly. no port is used. table 14. wdt.c functions function description and comments void init_wdt(void); wdt initialization. it must be used before any use of the wdt. it initializes the value loaded into the prescaler and into the counter. to use the wdt in output mode, you must initialize the output pin in push pull, alternate function . this means (pxc0r,pxc1r,pxc2r) = (1,1,0) void start_wdt(void); start the watchdog timer. void stop_wdt (void); it stops the counting of the timer (useless in watchdog mode). void restart_watchdog(void); this routine refreshes the watchdog counter: at each end of count, if this function has not been used before, a reset is generated internally. the periodic use of this function is the only way to avoid a reset. void init_wdt_it(void); this routine configure the interrupts after each end of count using inter- rupt channel inta0. nmi is thus configured as the top level interrupt. don't forget to initialize your start-up file correctly. void enable_wdt_it(void) enable the wdt interrupt. void intwdt_endcount(void); interrupt subroutine which occurs after an end of count. the code written in the user part allow the generation of a simple pwm signal (programmable duty cycle). function description and comments void init_wdt(void); wdt initialization. it must be used before any use of the wdt. it initializes the value loaded into the prescaler and into the counter. void start_wdt(void); start the watchdog timer.
111/146 ST9 user guide void stop_wdt (void); it stops the counting of the timer (useless in watchdog mode). void restart_watchdog(void); this routine refreshes the watchdog counter: at each end of count, if this function has not been used before, a reset is generated internally. the periodic use of this function is the only way to avoid a reset. function description and comments
112/146 ST9 user guide 5 using the development tools 5.1 developing in c language although the ST9 c compiler is an optional product, you are strongly advised to write your software using a high level language. naturally for the sake of optimization, especially to ob- tain the best execution times from certain frequently-used pieces of code, assembly language will still remain the right choice. this will be true at least for the initialisation file. but writing a complete program in assembler has few advantages and many drawbacks, so there can be no economic justification for using only assembler. this is why some of the examples in this guide are written in assembler and some in c. the development tools allow you to mix both languages easily. a useful book, if you have some experience of c language is ? the c language ? , by kernighan and ritchie, second edition. 5.2 available tools the following tools are available for the ST9 family: ? a software development package, named gnu9p, that includes a c-compiler and a make utility. ? a range of emulators for the various sub-families. you have two options in terms of development tool products. a software development package is delivered with each emulator. this does not include the c-compiler. you must pur- chase it separately. so with the emulator package alone you can only do assembler program- ming. as previously mentioned, you are strongly advised to use c programming as much as pos- sible, for the obvious reasons of structuring the source code, of code portability and reus- ability. in addition, developing the program is much easier and more reliable due to the con- trols and checks performed by the c-compiler. however, in the event that a program requires very fast processing, the c language is imprac- tical so the program must be carefully written in assembly language another point worth mentioning is the development environment, which is the part of the soft- ware that deals with the production and the modification of the source files.
113/146 ST9 user guide 5.3 introducing the development tools the ST9 software toolchain v6 allows complex applications to be developed easily and effi- ciently for the ST9 family of microcontrollers. it is designed to provide the user with a powerful development environment which can be used to design, debug, maintain and develop appli- cations in the c and assembly languages. in addition to the c compiler, assembler and linker, the ST9 software toolchain v6 provides an integrated development environment (ide) that is used to edit, build and debug an application in a single environment. using the ST9 software toolchain v6, it is possible to develop applications in the c language without being hindered by the segmented architecture of the ST9 microcontroller. applications can be as large as 4 mb of code and data, and can be completely written in c language as if developing standard c programs. this code is linked with the standard start-up code that ini- tializes the ST9 microcontroller. depending on the application board, the startup files may need to be customized to ensure initialization. with this software toolchain, variables can be handled in the ST9 register file as if they were in memory, handling variables in this manner dramatically reduces the size of code. objects in memory can be controlled either at a modular level or on an object by object basis. thanks to the powerful features of the debugger, such as advanced breakpoints, break on registers, trace with 64k records and performance analysis, the debugging and tuning of an application is made easier and quicker. the ST9 software toolchain v6 is designed for use with the ST9 hds2v2 emulators. to obtain further information about the toolchain, please refer to the toolchain docu- mentation. 5.4 program configuration and initialisation most programs are divided into several source files. this makes modifications easier and re- compilation quicker, using the make utility that recompiles only the files that have changed since the last compilation. how you split the source text into files is a matter of taste. however, a few rules are worth fol- lowing for keeping things well organized. they are: ? for sake of portability, assembler source text must not be mixed with c source text in the same file. in actual practice, assembly statements may be written in c, but reduce these to a minimum. ? code that is very low-level is very machine-dependent. this code should be in one or more specific files. one or several higher levels of code can be defined according to the application. this is up to you, but in all cases, machine-specific code, even written in c, should not reside in the same
114/146 ST9 user guide file as a higher-level code. this is used to change the hardware configuration (assignments of the port pins, etc.) by changing only those files that are involved with low-level routines. once this layout is established, you can then write the files mentioned below. these files are used to configure the tools. since they know the program structure, it can be maintained by compiling the right portions whenever they change. so you absolutely have to go through the following steps even though they are not directly related to writing code: ? writing the makefile ? writing the linker command file ? writing the start-up file these files are specific to each project and must be added to the list of source files. examples are given in the applications described in this book and are available in the companion soft- ware. 5.4.1 writing the makefile the makefile is the template that puts all the program pieces together. it describes the module interdependencies that enable the gmake utility to build the program efficiently by processing only those source files that have been modified since the last invocation of gmake (6) . the make language is very powerful, for a make utility can be applied to almost any kind of processing where several files provide a single result. it is a generic machine that manages updates smartly. when developing programs for the ST9, the makefile description is similar from one project to another. most of the changes relate to the name and the number of the files involved. thus, we propose here a skeleton makefile and we explain how you can tailor it for a specific application, without going into the advanced features gmake offers. a skeleton makefile is given on the companion software, and a variant is included in the direc- tory of each application. this will help you understand typical makefile usage, which is not dif- ficult to learn. the skeleton makefile reads as follows: #/*******************************/ #/* makefile skeleton */ #/*******************************/ # defines # ******* (6) see gnu9p make utility manual.
115/146 ST9 user guide # here you declare your compilation options cflags = -m$(model) -i$(incdir) -c -g -wa,-alhd=$*.lis # here you declare your linking options ldflags = -nostdlib -t$(scriptfile) -wl,-map,$(appli).map # define here the name of your application without any extension appli = # here you specify the memory model used by your application (compact/ specmed/medium) model = # here you give the name of the script file used by your application scriptfile = # give here the name of the c/spp/asm source files used in the application c_src = spp_src = asm_src = # give here the name of the startup files used in the application startup_src= # list of directories to be searched vpath = # location of include files. do not leave this variable empty. # if you do not need it, remove or comment it. incdir = # common defines # ************** # name of file containing dependencies.
116/146 ST9 user guide # this file is automatically generated by this makefile dep = $(appli).dep # the gcc9 driver is used for running the compiler, assembler, linker gcc = gcc9 # list of object files objs = $(patsubst %.spp,%.o,$(filter %.spp,$(startup_src))) \ $(patsubst %.asm,%.o,$(filter %.asm,$(asm_src))) \ $(patsubst %.spp,%.o,$(filter %.spp,$(spp_src))) \ $(patsubst %.c,%.o,$(filter %.c,$(c_src))) # rule for building the target $(appli).u : $(objs) $(libs) $(scriptfile) $(gcc) $(ldflags) $(objs) $(libs) -o $@ # rules %.o:%.c $(gcc) $(cflags) $< -o $@ %.o:%.asm $(gcc) $(cflags) $< -o $@ %.o:%.spp $(gcc) $(cflags) $< -o $@ include $(appli).dep # rule for forcing the build without taking into account dependencies rebuild: gmake -f $(appli).mak clean gmake -f $(appli).mak $(appli).u # rule for making dependencies file
117/146 ST9 user guide $(dep): $(c_src) $(spp_src) @echo generating dependencies ... $(gcc) -mm -i$(incdir) $^ > $@ # rule for cleaning the application .phony : clean clean : @echo off if exist *.o del *.o if exist *.u del *.u if exist *.lis del *.lis if exist *.map del *.map if exist *.dep del *.dep if exist *.hex del *.hex the syntax of this file looks complicated. in fact, you typically only have to change the de- fines section. the various items of the file are detailed below. 5.4.1.1 cflags = -m$(model) -i$(incdir) -c -g -wa,-alhd=$* .lis cflags is a variable that contains the options that govern the working of the c-compiler. re- ferring to the option table of the compiler, it means: 5.4.1.2 ldflags = -nostdlib -t$(scriptfile) -wl,-map,$(appli).map ldflags is a variable that contains the options that govern the working of the linker. the op- tions are: option meaning -m$(model) defines the memory model to use. -i$(incdir) defines user header files path. -c output an object file for later linking. -g include in the object file all necessary information for the debugger to allow it to use symbolic names. -wa,-alhd=$*.lis tells the gcc9 to transmit the option string -alhd=$*.lis to the assembler. these op- tions makes the assemble generate the most complete assembly listing file to help finding problems more easily. option meaning -nostdlib inhibits the use of standard startup files or libraries. -t$(scriptfile) tells the linker to use the specified script file. -wl,-map,$(appli).map tells gcc9 to transmit the -map $(appli).map option string to the linker. this option will make the linker print a link map in the map file.
118/146 ST9 user guide 5.4.1.3 appli = ... this variable must contain the name of the main object file and related files, which are: example: appli = smcb generates smcb.u and smcb.map using the script file to define the linker behavior. 5.4.1.4 scriptfile = ... this variable must contain the name of the script file to be used during the linking process. 5.4.1.5 c_src = ... this variable must contain the complete list of the c source files involved in the program to be built. example: c_src = main.c config.c serial.c calcul.c encoder.c 5.4.1.6 spp_src = ... this variable must contain the complete list of spp source files involved in the program to be built. spp are assembler source files needing preprocessing. example: spp_src = register.spp decoder.spp 5.4.1.7 asm_src = ... this variable must contain the complete list of the assembler source files involved in the pro- gram to build. example: asm_src = startup.asm interrup.asm 5.4.1.8 startup_src = ... this variable must contain the complete list of the startup files involved in the program to be built. example: startup_src = crtbegin.spp crtend.spp 5.4.1.9 vpath = ... this variable must contain the list of directories that the make function should search. ex- ample: vpath = ..\src ..\startup file name type of file
.u object file ready for loading into the emulator. this is defined in conjunction with the ld9 script file.
.map the memory map file name.
119/146 ST9 user guide 5.4.1.10 incdir = ... this variable must contain the list of directories that contains header files needed by the pro- gram. example: incdir = ..\include ..\header 5.4.1.11 make rules a make rule is a statement that both tells which file is dependent on which other file, and the processing needed in order to update the result file when the source file has changed. all files written under ms-dos are marked in the directory with a date/time stamp. this allows the make utility to compare dates between files. if a file declared in a rule as being the result of a source file, and the source file has a later date than that of the result, the result must be regenerated. for example, in the following rule: %.o:%.c $(gcc) $(cflags) $< -o $@ the first line says that any file with extension .c is the source for the corresponding .o file, so that if the .c file is younger than the .o file, the source file must be recompiled. the second line says that the compilation is done using gcc9, with the options stored in the cflags variable, that the input file "$<" is the .c file (source file), and the output file "$@", specified by option -o, is the target file. 5.4.2 writing the linker command file using a script file the linker uses the linker command file (7) (or script file) to correctly position the code and vari- ables in the memory spaces. it defines the start and end of the rom and ram area(s), and gives the list of the object files to be linked. it also generates the appropriate labels to allow c variables to receive their initial values before the program starts. once the script file is written, the only thing you have to do is to add new file names or change the mapping. below is an example of a generic script file for an ST92f150: memory { flash0 : origin = 0x000000, length = 8k flash1 : origin = 0x002000, length = 8k flash2 : origin = 0x004000, length = 48k flash3 : origin = 0x010000, length = 64k, mmu = idpr0 idpr1 (7) ST9 family gnu software tools, second part: ld9.
120/146 ST9 user guide eeprom : origin = 0x220000, length = 1k, mmu = idpr2 ram : origin = 0x200000, length = 4k, mmu = idpr3 regfile (t) : origin = 0x00, length = 208/* groups 0 to 0x0c */ } sections { _stack_size = defined(_stack_size) ? _stack_size : 0x100; .init : { *(.init) }> flash0 .text : { *(.text) }> flash0 .fini : { *(.fini) }> flash0 .secinfo : { create_secinfo_table }> flash0 .rodata : { *(.rodata) }> flash0 .data : at (loadaddr(.rodata) + sizeof (.rodata)) { *(.data) }> ram .bss : { *(.bss) *(common) }> ram .stack : { _stack_start = defined( _stack_start) ? _stack_start : . ; . = . + _stack_size ; _stack_end = _stack_start + _stack_size ; }> ram
121/146 ST9 user guide .fardata : at (loadaddr(.data) + sizeof (.data)) { *(.fardata) }> ram .reg16_data :at (loadaddr(.fardata) + sizeof (.fardata)) { *(.reg16_data)} > regfile .reg16_bss : { *(.reg16_bss)} > regfile .reg8_data :at (loadaddr(.reg16_data) + sizeof (.reg16_data)) { *(.reg8_data) }> regfile .reg8_bss : { *(.reg8_bss)} > regfile } for more details on the command file, refer to the command language section in the gnu software tools user manual. 5.4.3 writing the start-up file this file is the very first file executed at power on. it performs the initialisation procedure re- quired for the processor to start. it differs according to whether the program includes modules written in c or not. in all cases, it includes two main parts: ? the reset, exception and interrupt vectors. ? the initialisation code that is required for the program to start. 5.4.3.1 vector table the vectors consist of the reset vector, the divide by zero vector and the other interrupt vec- tors. they are placed at defined addresses: ? the reset vector must be located in the first word of the first segment. ? the divide by zero trap must be placed at address 2 in each segment where a program uses division. each segment containing programs using division must have its own address trap branched to a local routine making only a ? calls divide_by_zero ? far call to the divide by zero service routine located in a single segment.
122/146 ST9 user guide ? all the other interrupt addresses must be placed in the interrupt segment. in ? ST9 ? mode, interrupt service routines can make far calls to other segments. they are organized as follows: table 15. segment 0 table 16. segment n (not interrupt segment) table 17. interrupt segment the vectors above are placed at these addresses by hardware. you can place the following ones at will, except that for each peripheral they must obey some rules like being a multiple of a given number, e.g. 8 for the sci. to force the linker to effectively position these vectors from address zero, the start-up module must first be included in the module list in the linker command file. address cause point to 0 reset (action on the reset pin, watchdog reset or software reset). the start of the initialisation code. the reset address is the start-up address. 2 divide by zero address of the routine in segment 0 that handles the case where a division by zero has occurred. address cause point to 2 divide by zero address of the routine in segment n that handles the case where a division by zero has occurred. address cause point to 2 divide by zero address of the routine in segment isr that handles the case where a division by zero has occurred. 4 top level interrupt the interrupt service routine for the top level interrupt. ... interrupt interrupt service routine addresses. address cause point to n first cause for the peripheral whose ivr is set to n the routine that handles the first interrupt cause for that pe- ripheral. n+2 second cause for the periph- eral whose ivr is set to n the routine that handles the second interrupt cause for that peripheral. etc.
123/146 ST9 user guide 5.4.3.2 initialisation code the initialisation code mainly has to initialise the core. the core contains certain control regis- ters that must be set to correct values or the program will fail to start. they are listed in the table below. they are in the order they are initialized in a typical start-up file, though this order is somewhat arbitrary. register number register name function (*) comments 235 moder selects the space where the stacks re- side (register file or memory), main clock divider on/off, clock prescaler division rate. if power and electromagnetic interference are not a concern, the prescaler can be set to zero so that the processor runs at full speed. otherwise, the speed/ consumption trade-off can be handled at will accord- ing to the needs of the program. 231 flagr selects the single space of twin-space mode for the memory. in the ? ST9 ? mode the dp bit of this register selects program memory when cleared, or data memory when set. it must be changed using the sdm and spm instructions. typically, one of these is used at the be- ginning of the program and remains unchanged after- wards. on some occasions, it may be changed, for example to access tables of constants in rom if two spaces are used. therefore in ? ST9 ? mode, dp must be set with the sdm instruction (used only once in the start-up pro- gram) to set the use of dpr register to address data memory. the spm instruction must not be used. to access data through the csr register, use the ldpd, lddp or ldpp instruction. 238-239 ssp position of the top of the system stack in memory or register file no subroutine or function call may be performed be- fore the initialisation of ssp and moder. note that since a call first decrements the stack pointer by two and then writes the return address, if the stack is po- sitioned in the register file, it may be initialised to the register number of the top of stack + 1 to save stack space. 236-237 usp position of the top of the user stack in memory or register file. unused if only one stack is used. 232-233 rp0-rp1 selects the mode for the working registers as well as the abso- lute register numbers for r0 and r8. these registers are set using the srp, srp0 and srp1 instructions. see the description of working registers in section 3.1.4 .
124/146 ST9 user guide 230 cicr enables the mfts, enables the inter- rupts, selects the ar- bitration mode (concurrent mode or nested mode), and the priority level of the main program. the gcen bit of this register enables all the mfts at once. it may also be set once the mfts are all initial- ised, if it is desired that they be synchronised or that they do not start before the remainder of the program is ready. the ien bit enables all the interrupts at once. again, it may be set now, or only when the remainder of the program is ready to process them. the iam bit selects either concurrent mode or nested mode. it is better to do it now. the three bits, cpl2 to cpl0, set the level of the main program. its value depends on the structure of the program. typically, it is set to 7, since the main program is likely to be the low-priority process. see the paragraph on interrupts in section 3.4 . 234 ppr sets the page number for the paged register group; set to zero. this register will probably be changed several times during the execution of the program. it is first set now, if the wcr needs to be initialised. 250 page 0 wdtpr prescaler register of the watchdog timer. if the wdt is used as a watchdog ( ? ) , it should be ini- tialised before the wdgen bit is cleared in the wcr register below. in this case, it is advisable to initialise it right now. see note for values. 248-249 page 0 wdthr+w dtlr reload register of the wdt. same note as above. 251 page 0 wdtcr mode control register of the wdt. same note as above. 252 page 0 wcr starts (or not) the watchdog function of the wdt, selects the wait states for exter- nal memory access independently for up- per and lower memo- ries. if you use the watchdog function, first initialise the watchdog timer. you can start it later using the wdgen bit of this register, but no protection is on be- fore this time. the external memory access is set by default to the maximum number of wait states to allow the program to start. you should reduce it to the exact number re- quired by the type of memory to achieve maximum performance. (*) some register functions may not be mentioned if not relevant for the initialisation. ( ? ) device datasheet; 9 register number register name function (*) comments
125/146 ST9 user guide once you have set these registers, the core is in good shape to start work. the next task is to initialise the data memory and/or register file by entering a loop that writes zeroes into all lo- cations used for data storage. this may seem superfluous, but there are two reasons for this: ? in c language, any non-initialized variable is supposed to contain zero at as an initial value. ? in any case, this makes the program behavior reproducible, even if not all variables are ini- tialized explicitly. then, the table of initial values for the initialized variable (in the c language sense) is copied to the location in ram where the variables are positioned. the linker puts the initial values in the same order as the variables in ram, so a mere block copy is sufficient for this initialisation. eventually, the entry point of the main program written in c or assembler can be called. the main program should be a closed loop and should not return. typically in the start-up code, the call to the main routine is followed by a halt instruction. 5.4.3.3 start-up file customization a generic start-up file is included with the toolchain: crtbegin.spp. this file has to be modified in order to fit the needs of your application. in most cases, only two parts should be modified: part 2 (interrupt vectors declaration) and part 6 (mmu setup). note: the start-up file initializes the ? ST9 ? mode (encsr bit of emr2 to 0) to be compatible with the previous ST9 version. in the main program you have to initialise this bit to 1 for ? ST9 ? mode if you want the mmu working with segments during interrupts.
126/146 ST9 user guide 5.4.3.3.1 part 2: interrupt vector declaration /* +------------------------------------------------------------+ | part 2: interrupt vector declaration | +------------------------------------------------------------+ */ ; interrupt vector definition ; absolute address 0 is assumed (. == 0x0000) .word __reset ; address of reset routine .word divide_by_zero_trap_label ; address of the divide by zero ; trap routine .org 0x06 .word 0xffff ;no external watchdog used .rept 126 .word __default_interrupt_handler; default interrupt handler ; routine .endr ; end of macro definition the start-up file defines the reset vector and the divide by zero trap vector. all other vectors are directed to a default interrupt handler. a new vector must be defined for each interrupt routine of the user program. the vector loca- tion must match the corresponding ivr register. example: .word __reset ; address of reset routine .word divide_by_zero_trap_label ; address of the divide by zero ; trap routine .org 0x06 .word 0xffff ;no external watchdog used .org 0x56 .word intsci_transmitready .org 0x100
127/146 ST9 user guide 5.4.3.3.2 part6: mmu setup /* +------------------------------------------------------------+ | part 6: mmu setup | +------------------------------------------------------------+ */ #if defined(medium) ; ; initialisation of registers controlling external memory interface ; emr1 reset value is x000-000m ; mc, ds2en, asaf, nmb, et0, bsz should be checked against user ; memory configuration and emr1 set accordingly ; ; emr2 reset value is m000-1111 ; encsr is 0, which selects ST9 compatibility mode for interrupt handling. ; dmemsel, pas1, pas0, das1 and das0 should be checked against user memory ; configuration and set complementary to wcr in page #0 (see below) ; dprrem is forced to one to have dpri registers accessible in group e ; or emr2, #emr2_dprrem ; remap data page registers ; ; initialization of dpr registers with initial value ; ld dpr0, #_idpr0 ld dpr1, #_idpr1 ld dpr2, #_idpr2 ld dpr3, #_idpr3 #else /* medium */ ;
128/146 ST9 user guide ; initialization of dpr registers with initial value ; ld dpr0_p, #_idpr0 ld dpr1_p, #_idpr1 ld dpr2_p, #_idpr2 ld dpr3_p, #_idpr3 #endif /* medium */ #if defined(medium) || defined (specmed) ; encsr is 1, use csr for interrupt handling. or emr2, #emr2_encsr ; enable csr during interrupts #endif /* medium */ #if defined(compact) ; in compact programming model, the startup file ; will assumes that csr = isr, set by the bootrom #endif /* compact */ .endproc in this part, the user only needs to comment dpr register initialization lines if one or more dprs does not map a memory region.
129/146 ST9 user guide 5.5 global initialisation: core and peripherals 5.5.1 core initialisation set the lower program memory addresses to the addresses of the interrupt service routines that the peripherals will use. initialise the core, as shown above. initialise the pll. if the multifunction timers are to work synchronously, you must start them at the same time. to do this, reset the global counter enable bit (gcen, bit 7 of register cicr) before the mfts are ini- tialised. then set it just before the main program starts. initialise the memory. this may include: resetting the register file and/or the data memory to zero, and preloading the variables with the initial values. the procedure to follow when programming in c is described above. 5.5.2 peripheral initialisation it is now time to configure the peripherals. for each one, you must take the following steps: set the page pointer register to the page that contains the peripheral's registers. on some peripherals, several pages are involved so set the page pointer register accordingly. set the various registers that define the behavior of the peripherals. in some cases, you have to set them in a certain order. refer to the appropriate data sheet. do not yet set the bits that start the peripheral working. set the interrupt vector register of each peripheral to point to the corresponding group of pointers to the interrupt service routines in program memory. you can now set the interrupt mask register, since the global interrupt enable bit is reset. if you are using dma, set the dapr and dcpr registers to point to two registers in the reg- ister file. then: ? initialise the address register to the address of the buffer in which the data is to be stored. ? set the counter register to zero to inhibit dma transfers. you can now set the peripheral enable bit or start bit, unless you only want it to start later (as can be the case with the watchdog timer).
130/146 ST9 user guide 5.5.3 port initialisation when you have configured all the peripherals as described above, you should initialise the ports to your requirements: input or output, open drain or push-pull, ttl or cmos levels, etc. for the parallel i/o ports. you must set the port pins that serve as inputs or outputs for peripherals as either: ? alternate function for peripheral outputs, or ? regular input for peripheral inputs the exception is the a/d converter, where you must set the input pin as alternate function. 5.5.4 final initialisation install the working registers in the group defined for the main program. set the page pointer register to a default value. set the global counter enable, the global interrupt enable and, if required the watchdog function. the main program is now ready to run. 5.6 interrupt considerations the ST9 has two main paging registers: ? the rpp register pair that selects the working register group ? the ppr register that selects one of 256 pages within register group 15 these registers are essential to the correct working of the program. when an interrupt occurs, it is likely you will have to change either or both of these registers. this is why you must push them to the stack on entry, and pop them back on exit. an interrupt is requested by a bit in a register of a peripheral. this bit is not reset automatically by the fact that the interrupt is serviced. you must reset it in the code of your interrupt service routine. if you write an interrupt service routine in c, by default ppr and all registers used by the rou- tine are pushed on the stack. this can be time-consuming. if your program is entirely written in c, and you use none or few registers explicitly, the register file has enough room to allocate a private working register group for each interrupt service routine. you specify this by a #pragma pseudo-instruction. this method provides the fastest response times.
131/146 ST9 user guide 6 detailed block diagrams here are the detailed block diagrams to supplement to the simplified ones used at various points throughout this book. 6.7 external interrupt controller figure 47 . external interrupt block diagram int 0 pin end of count wdr see timer watchdog and reset circuitry rising (set) or falling (reset) edge trigger event watchdog or int 0 pin 1 0 int a0 interrupt to the core 0 1 interrupt pending bit: channel a0 comparison between cpl and priority level of int a0 0' for inta0' these bits are the msb of the pointers in the vector table, for the 8 external interrupts. from another interrupt source; hardware interrupt daisy chain ien is common for the 8 external maskable interrupts (see the priority level arbitration) 0 ted1 ted0 tec1 tec0 teb1 teb0 tea1 tea0 7 eitr (r242 page 0) external interrupt trigger event register ipd1 ipd0 ipc1 ipc0 ipb1 ipb0 ipa1 ipa0 imd1 imd0 imc1 imb1 imb0 ima1 ima0 interrupt mask bit channel a0 tea0 : trigger event of interrupt channel a0 iaos : interrupt a0 selection bit ipa0 : interrupt pending bit channel a0 (set and reset by hardware, except if one wishes a software interrupt) ima0 : interrupt mask bit channel a0 cpl (0,1,2):current priority level of main pl (1a,2a):priority level of group inta0, inta1 ien : interrupt enable level of int a0 0 v7 v6 v5 v4 tltev tlis iaos ewen 7 eivr (r246 page 0) external interrupt vector register (see vector table organisation) 0 7 eipr (r243 page 0) external interrupt pending register 0 7 eimr (r244 page 0) external interrupt mask-bit register imc0 pl2d pl2c pl2b pl1b pl2a pl1a 0 7 eiplr (r245 page 0) external interrupt priority level register pl1c gcen tlip tli iam cpl2 cpl1 cpl0 0 7 cicr (r230) central interrupt control register ien pl1d
132/146 ST9 user guide 6.8 top-level interrupt input figure 48 . top-level interrupt block diagram nmi pin rising (set) or falling (reset) edge trigger event on nmi pin watchdog or nmi pin top level interrupt 1 0 a pseudo nmi event interrupt a real event or top level interrupt to the core tli routine has no interrupt vector register. isr routine in vector table: byte4 (high), byte 5 (low) by hardware. tltev: top level trigger event bit tlis: top level interrupt selection bit tlip: top level interrupt pending bit (set and reset by hardware only) tli: top level interrupt bit ien: interrupt enable tlnm: top level not maskable 0 1 choosing between end of count wdr see timer watchdog and reset circuitry 0 v7 v6 v5 v4 tltev tlis iaos ewen 7 eivr (r246 page 0) external interrupt vector register 0 gcen tlip tli ien iam cpl2 cpl1 cpl0 7 cicr (r230) central interrupt control register 0 hl5 hl4 hl3 hl2 hl1 hl0 7 nicr (r247 page 0) nested interrupt control register 0 tlnm 7 nested interrupt control register hl6 interrupt nmi
133/146 ST9 user guide 6.9 watchdog timer figure 49 . watchdog timer block diagram wdtin pin input modes and clock control logic intclk / 4 prescaler and counter registers control logic wdt clk output control logic end of count wdout pin nmi pin int 0 pin inta 0 request reset to the core top level interrupt request eivr (r246, page 0) external interrupt vector register 0 0 1 1 prs7 prs0 wdtpr (r250 page 0) timer / watchdog prescaler register prs latch (read/write) r15 r0 wdtr (rr248 page 0) timer / watchdog 16-bit down counter counter latch (rr248 write only) 7 0 0 15 current value (rr248 read only) prs current value wcr (r252, page 0) 0 7 wait control register x wdgen wdm2 wdm1 wdm0 wpm1 wpm0 wpm2 0 7 v7 v6 v5 v4 tltev ioas ewen tlis st_sp s_c inmd1 inmd2 inen outen wrout outmd wdtcr (r251 page 0) timer/watchdog control register 70 st_sp : start/stop bit s_c : single-shot/continuous inmd1,2 : input mode selection bit inen : input enable outmd : output mode wrout : write out outen : output enable bit wdgen : watchdog enable bit (active low) tlis : top level input selection bit iaos : interrupt channel a0 selection bit top level
134/146 ST9 user guide 6.10 multifunction timer figure 50 . multifunction timer block diagram up/down logic trigger up (txina) trigger down (txinb) up / down (txina) autodiscrimination clock up (txina) clock down (txinb) 8-bit prescaler prescaler register gate 3 internal clock external clock either txina or txinb or both of these inputs ext. clock 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 not used not used gate gate not used trigger gate trigger clock up up / down trigger up up / down autodiscrim. trigger ext. clock trigger not used trigger not used trigger ext. clock not used ext. clock trigger clock down ext. clock trigger down not used autodiscrim. ext. clock trigger gate txina pin txinb pin 0 0 nop 0 1 1 0 1 1 and txina / txinb configuration (inputs in alternate function) txouta pin txoutb pin see operating modes of the mft block diagram * mft0 registers, page 10 mft1 registers, page 8 (st 9030 / 9040) in3 in2 in1 in0 a0 b1 b0 a1 icr (r250*) external input control register 70 txina trigger input function txinb input function prsr (r251*) p7 p0 0 7 b0 b1 b0 b1 b0 op cev b1 oacr (r252) output a control register 70 b0 b1 b0 b1 b0 op cev b1 obcr (r253) output b control register 70 on-chip event signal on ovf preset value or current level on txoutb pin on-chip event signal on cmp0r preset value or current level on txouta pin successful event on mft action on txouta or txoutb set toggle reset nop b0 0 0 1 1 b1 0 1 0 1 tmr (r253) timer mode register bits 6 and 7 oe1 oe0 7 6 txout a enable txout b enable
135/146 ST9 user guide figure 51 . mft operating modes block diagram up/down logic 16-bit counter with comparator reg0hr, reg0lr (r240, r241*) reg1hr, reg1lr (r242, r243*) capture load register 1 u / d clock clear dma controller capture 0 load 1 compare 1 compare 0 clear logic ovf / unf load / capture / monitor logic 0 retrigger mode 1 trigger mode compare logic * mft0 registers page 10 mft1 registers page 8 (st 9030 / 9040) (see i / o modes of the mft bloc diagram) counter enable (see i / o modes of the mft bloc diagram) oe1 oe0 bm rm1 rm0 co ren eck tmr (r249*) timer mode register 1x0 1x1 000 010 001 011 biload bicapture load load capture capture monitor capture monitor capture reg0r reg1r 0 continuous mode 1 one-shot mode 7 0 cp0 cp1 cm0 cm1 ouf a0 ocm0 ocp0 flagr (r254*) flags register 7 0 capture interrupt function 1 and 0 or cm0 cp0 0 parallel mode not selected 1 parallel mode selected r15 r0 0 15 capture load register 0 r15 r0 0 15 cmp1hr, cmp1lr (r246, r247*) compare 1 register r15 r0 0 15 cmp0hr, cmp0lr (r244, r245*) compare 0 register r15 r0 0 15 dma controller cen ccp0 ccmp0 ccl udc cs of0 udcs tcr (r248*) timer control register 7 0 capture 1 counter status load 0 1
136/146 ST9 user guide 6.11 adc figure 52 . analog to digital converter block diagram interrupt unit int. vector pointer int. control register compare result register threshold h/l register bu threshold h/l register bl threshold h/l register ah threshold h/l register al compare logic data register h/l15 data register h/l14 data register h/l13 data register h/l12 data register h/l11 data register h/l10 data register h/l 9 data register h/l 8 successive analog to digital analog mux ain 15 ain 14 ain 13 ain 12 ain 11 ain 10 ain 9 ain 8 conversion result autoscan logic control reg.2 control logic internal trigger external trigger control reg.1 data register h/l 7 data register h/l 6 data register h/l 5 data register h/l 4 data register h/l 3 data register h/l 2 data register h/l 1 data register h/l 0 ain 7 ain 6 ain 5 ain 4 ain 3 ain 2 ain 1 ain 0 approximation 10 bit analog section ck prescaler ckad intclk (from mft0) (extrg) (clr2) (clr1) converter
137/146 ST9 user guide 7 glossary a a/d analog to digital ac alternating current acr address compare register adc analog to digital converter adtr a/d trigger ain analog input awd analog watchdog b brg bit rate generator c ccu clock control unit chcr character configuration register cicr central interrupt control register clk clock clr control logic register cmos complementary metal oxide silicon cmp compare register cpl current priority level cr carriage return crr compare results register cs chip select d dapr dma address pointer register dc direct current dcpr dma counter pointer register
138/146 ST9 user guide di data in dil dual in line dma direct memory access do data out dp data page e ecv end of conversion eeprom electrically-erasable prom eimr external interrupt mask-bit register eiplr external interrupt priority level register eipr external interrupt pending register eitr external interrupt trigger register eivr external interrupt vector register ewds erase or write disable ewen erase or write enable f flagr flag register g gcc9 gnu c compiler for ST9 i i/o input/output iam interrupt arbitration mode icr external input control register idcr interrupt/ dma control register idmr interrupt/ dma mask register idpr interrupt/dma priority register
139/146 ST9 user guide ien interrupt enable inmd interrupt mode int interrupt iocr i/o connection register isr interrupt segment register or interrupt service routine ivr interrupt vector register l lcd liquid crystal display led light emitting diode lf line feed lsb least significant bit m mft multifunction timer mmu memory management unit moder mode register msb most significant bit n nicr nested interrupt control register nmi non-maskable interrupt o oacr output a control register obcr output a control register ovf overflow p pc program counter or personal computer pfe programmer ? s file editor ppr page pointer register
140/146 ST9 user guide prl priority level prom programmable rom pwm pulse width modulator pxc port control register pxdr port data register r ram random access memory rccu reset and clock control unit rom read-only memory rpp working register pointer rxclk receiver clock input rxdata receiver data s seg extract the 6 bits segment of a label sci serial communications interface sck serial clock sof extract the 16 bits offset of a label spi serial peripheral interface spicr spi control register spidr spi data register srp set register pointer sspr system stack pointer register t tcr timer control register tlnm top level not maskable tmr timer mode register ttl transistor to transistor logic
141/146 ST9 user guide txclk transmitter clock input txd transmitter data u u/d up/down uart universal asynchronous receiver/transmitter unf underflow uspr user stack pointer register uv ultraviolet w wdt watchdog timer wdtcr watchdog timer control register wdtlr watchdog timer low register wdtpr watchdog timer prescaler register
142/146 index index a adc configuring the input pin ................... 67 detailed block diagram ................... 136 interrupt vectoring ............................ 100 address spaces overview .............................................. 14 addressing modes ..................................... 41 analog watchdog overview ............................................ 100 arguments passing arguments in c ................... 40 arrays accessing ............................................ 41 awd bit ..................................................... 100 b bit rate generator ....................................... 92 block copy .................................................. 41 c causes interrupt causes ................................. 44 c-compiler ................................................ 112 ccu clock control unit ............................. 60 character matching sci ....................................................... 93 cicr overview .............................................. 47 clock selection mft ...................................................... 75 compare result register ....................... 100 concurrent mode ....................................... 48 interrupts ............................................. 47 context switching .............................. 17, 130 continuous mode wdt ..................................................... 71 wdt example .................................... 73 control registers example of programming ................. 65 copy block copy ........................................... 41 core overview .......................................... 7, 14 cpl overview .............................................. 47 cpuclk cpu clock ........................................... 60 csr code segment register ................... 24 d dcpr .......................................................... 58 development tools .................................. 112 overview ............................................ 113 divide instructions ..................................... 37 dma using in conjunction with the uart 93 dma controller application ........................................... 92 overview .............................................. 56 dmasr dma segment register ................... 27 driver i/o ........................................................ 66 e ecv bit ...................................................... 100 emulator .................................................... 112 enable interrupt enable flag .......................... 48 event counter mode wdt ..................................................... 69 examples context switching ............................... 17 divide instructions .............................. 37 dma application ................................ 92 interrupt initialisation ......................... 73 interrupt routine .................................. 56 ivr ....................................................... 44 lcd interface ..................................... 88
143/146 index makefile ............................................. 114 mft initialisation ................................ 85 mft interrupt vector .......................... 45 nested interrupts ................................ 49 parameter passing in c .................... 40 periodic interrupt timer application .72 programming peripheral control regis- ters ....................................... 65 programming peripheral registers .. 65 pwm application ................................ 82 pwm output ........................................ 79 selecting a register page .................. 22 test and jump ...................................... 38 test under mask ................................. 35 extract the page number of a data. ........ 29 f flagr register ........................................ 123 g gated input mode wdt ..................................................... 69 gnu9 ......................................................... 112 groups register groups ................................... 16 i i/o pins ........................................................ 66 i/o port configuration registers ...................... 67 ien bit .................................................... 48, 53 include files peripheral register definition ............ 66 initialisation global ................................................. 129 mft example ..................................... 85 stacks .................................................. 31 wdt ..................................................... 73 initialisation code ..................................... 123 instruction set overview .............................................. 33 intclk peripheral clock ................................. 60 interrupts adc ................................................... 100 analog watchdog ............................. 100 causes ................................................. 44 concurrent mode ......................... 47, 48 context switching ............................. 130 cpl ...................................................... 47 enable flag (ien) ............................... 48 external interrupt vectors ................. 55 external interrupts block diagram ... 52 external, detailed block diagram ... 131 initialisation example ......................... 73 interrupt routine example ........................................ 56 nested mode ................................ 47, 48 pins ...................................................... 51 priorities ............................................... 47 sci interrupt vectors ......................... 97 system overview ................................ 41 top-level interrupt ............................... 52 vectors ................................................. 43 isr iunterrupt segment register ........... 27 ivr example ............................................... 44 j jump test and jump ...................................... 38 l latency interrupt latency ................................. 47 lcd interface example ............................. 88 load instructions ....................................... 33 look-up tables implementing ...................................... 38 m make file example ................................... 114 make utility ........................................ 112, 114
144/146 index mask register interrupt and dma mask register .... 78 masking external interrupts .............................. 51 memory spaces overview .............................................. 14 moder register ................................ 31, 123 moving data blocks ................................... 33 multifunction timer detailed block diagram ................... 134 initialisation example ......................... 85 interrupt and dma mask register .... 78 interrupt vector example ................... 45 operating modes detailed block diagram 135 pwm example .................................... 79 swap mode ......................................... 58 multiplexing pins ....................................................... 54 n nested mode ........................................ 47, 48 example ............................................... 49 nmi ................................................... 47, 51, 52 p pag ............................................................. 29 parallel i/o .................................................. 66 parameter passing c language example ......................... 40 periodic interrupt application ................... 72 peripheral register pages ......................... 16 peripherals control registers programming example 65 list of main ............................................. 8 overview .............................................. 65 programming control registers ........ 65 register definition include files ......... 66 pins external interrupts .............................. 51 i/o pins ................................................ 66 multiplexing ......................................... 54 wdt output pin .................................. 71 pof extract the offset of the data address. 29 pointers register pointers ................................. 16 stack pointer ....................................... 31 port initialisation ....................................... 130 prescaler register mft ...................................................... 75 priority assigning to interrupt source ........... 47 external interrupts ............................. 51 interrupt priorities ............................... 47 interrupt priority mechanism ............ 41 top-level interrupt ............................... 52 processor core ....................................... 7, 14 pwm application example .......................... 79 pwm application example ....................... 82 r rccu reset and clock control unit .......... 60 realtime programming ............................. 47 register peripheral pages ................................ 16 register file overview .............................................. 15 register numbers table ............................ 19 register page number table .................... 21 register-oriented machine definition of ........................................... 7 register-oriented programming model overview .............................................. 14 registers definition include files ....................... 66 groups ................................................. 16 page selection example ................... 22 pointers ............................................... 16 working .......................................... 15, 16 retriggerable input mode wdt ..................................................... 70
145/146 index s sci theory of operation ............................ 92 seg extract the 6 bits segment of a label 24 serial communication interface overview .............................................. 92 serial peripheral interface interrupt vectors ................................. 97 overview .............................................. 88 single mode wdt ..................................................... 71 sof extract the 16 bits offset of a label .24 sources interrupt sources ................................ 44 srp instruction ............................................ 17 ssp ............................................................ 123 ST9040 block diagram .............................. 10 ST90r540 block diagram .................. 12, 13 stack overview .............................................. 31 stacks initialisation ......................................... 31 locating stack pointer in register ..... 31 location options .................................. 32 start-up file ............................................... 121 structures accessing ............................................ 41 swap mode multifunction timer ............................. 58 switching working registers ............................... 17 t test and jump ............................................ 38 test under mask ........................................ 34 timer block diagram ..................................... 68 event counter mode .......................... 69 gated input mode ............................... 69 output pin ............................................ 71 retriggerable input mode .................. 70 single/continuous mode ................... 71 triggerable input mode ...................... 70 tlnm bit ...................................................... 52 tools .......................................................... 112 top-level interrupt .................................... 52 block diagram ..................................... 53 detailed block diagram ................... 132 triggerable input mode wdt ..................................................... 70 u uart application ...................................... 92 usp ............................................................ 123 v vector table .............................................. 121 vectors example with mft ............................. 45 external interrupts ............................. 55 interrupt vectors overview ................ 42 w watchdog analog ................................................ 100 watchdog timer .................................... 51, 52 detailed block diagram ................... 133 output pin ............................................ 71 overview .............................................. 68 wdt initialisation example ......................... 73 periodic interrupt application ........... 72 working registers example ............................................... 17 overview ........................................ 15, 16 register pointers ................................. 16 switching ............................................. 17
146/146 ST9 user guide notes : information furnished is believed to be accurate and reliable. however, stmicroelectronics assumes no responsibility for the co nsequences of use of such information nor for any infringement of patents or other rights of third parties which may result from its use. no license is granted by implication or otherwise under any patent or patent rights of stmicroelectronics. specifications mentioned in this publicati on are subject to change without notice. this publication supersedes and replaces all information previously supplied. stmicroelectronics prod ucts are not authorized for use as critical components in life support devices or systems without express written approval of stmicroelectro nics. the st logo is a registered trademark of stmicroelectronics. all other names are the property of their respective owners ? 2004 stmicroelectronics - all rights reserved stmicroelectronics group of companies australia ? belgium - brazil - canada - china ? czech republic - finland - france - germany - hong kong - india - israel - italy - japan - malaysia - malta - morocco - singapore - spain - sweden - switzerland - united kingdom - united states www.st.com


▲Up To Search▲   

 
Price & Availability of ST9

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X